/*
 *  _________        _____ __________________        _____
 *  __  ____/___________(_)______  /__  ____/______ ____(_)_______
 *  _  / __  __  ___/__  / _  __  / _  / __  _  __ `/__  / __  __ \
 *  / /_/ /  _  /    _  /  / /_/ /  / /_/ /  / /_/ / _  /  _  / / /
 *  \____/   /_/     /_/   \_,__/   \____/   \__,_/  /_/   /_/ /_/
 *
 * Copyright 2005-2011 GridGain Systems, Inc. All Rights Reserved.
 */

var fadeInLastTimeout = null;
var fadeOutLastTimeout = null;
var showNextLastTimeout = null;

var ImageLoader = function(url){
    this.url = url;
    this.image = null;
    this.loadEvent = null;
};

/**
 *
 * @param element
 * @param type
 * @param expression
 * @param bubbling
 */
function addListener(element, type, expression, bubbling) {
    bubbling = bubbling || false;

    if (window.addEventListener) { // Standard
        element.addEventListener(type, expression, bubbling);

        return true;
    }
    else if(window.attachEvent) { // IE
        element.attachEvent('on' + type, expression);

        return true;
    }
    else
        return false;
}

/**
 *
 * @param imgId
 * @param imgSrc
 * @param incr
 * @param pause
 */
ImageLoader.prototype = {
    load:function() {
        this.image = document.createElement('img');
        var url = this.url;
        var image = this.image;
        var loadEvent = this.loadEvent;

        addListener(this.image, 'load', function(e) { if (loadEvent != null) loadEvent(url, image); }, false);

        this.image.src = this.url;
      },
      getImage:function() { return this.image; }
};

/**
 *
 * @param imgId
 * @param imgSrc
 * @param incr
 * @param pause
 */
function fadeInImage(imgId, imgSrc, incr, pause) {
    var img = document.getElementById(imgId);

    img.src = imgSrc;

    //setOpacity(img, 50);

    fadeIn2(imgId, 70, incr, pause);
}

/**
 *
 * @param objId
 * @param opacity
 * @param incr
 * @param pause
 */
function fadeIn2(objId, opacity, incr, pause) {
    obj = document.getElementById(objId);

    if (opacity <= 100) {
        setOpacity(obj, opacity);

        opacity += incr;

        fadeInLastTimeout = window.setTimeout("fadeIn2('" + objId + "'," + opacity + "," + incr + "," + pause +")", pause);
    }
}

/**
 *
 * @param imgId
 * @param imgSrc
 */
function fadeInImage2(imgId, imgSrc) {
    fadeInImage(imgId, imgSrc, 2, 30)
}

/**
 *
 * @param obj
 * @param opacity
 */
function setOpacity(obj, opacity) {
    opacity = (opacity == 100) ? 99.999 : opacity;

    // IE/Win
    obj.style.filter = "alpha(opacity:" + opacity + ")";

    // Safari<1.2, Konqueror
    obj.style.KHTMLOpacity = opacity / 100;

    // Older Mozilla and Firefox
    obj.style.MozOpacity = opacity / 100;

    // Safari 1.2, newer Firefox and Mozilla, CSS3
    obj.style.opacity = opacity / 100;
}

/**
 *
 * @param objId
 * @param opacity
 */
function fadeIn(objId, opacity) {
    fadeIn2(objId, opacity, 2, 30);
}

/**
 *
 * @param objId
 * @param opacity
 */
function fadeOut(objId, opacity) {
    obj = document.getElementById(objId);

    if (opacity > 0) {
        setOpacity(obj, opacity);

        opacity -= 2;

        fadeOutLastTimeout = window.setTimeout("fadeOut('" + objId + "'," + opacity + ")", 30);
    }
}

/**
 *
 * @param func
 */
function scheduleNext(func) {
    scheduleNext2(func, 7);
}

/**
 *
 * @param func
 * @param secs
 */
function scheduleNext2(func, secs) {
    showNextLastTimeout = window.setTimeout(func, secs * 1000);
}

/**
 *
 */
function clearLastTimeouts() {
    if (fadeInLastTimeout != null) {
        window.clearTimeout(fadeInLastTimeout);

        fadeInLastTimeout = null;
    }

    if (showNextLastTimeout != null) {
        window.clearTimeout(showNextLastTimeout);

        showNextLastTimeout = null;
    }
}

/*
 * Sets the display style of a given element to either "none" or "block",
 * hiding or displaying the element on the page.
 */
function toggleDisplay(id) {
    var e = document.getElementById(id);

    if (e.style.display != 'none') {
        e.style.display = 'none';
        e.style.visibility = 'hidden';
    }
    else {
        e.style.display = 'block';
        e.style.visibility = 'visible';
    }
}

/*
 * Opens up screencast window.
 */
function openScreencast() {
    window.open("screencast/grid_app_in_15min/screencast.html", "screencast1", 
        "toolbar=0,status=0,menubar=0,location=0,resizable=1,width=820,height=675");
}

/*
 * Opens up screencast window.
 */
function openJbossGridGainIntegrationScreencast() {
    window.open("screencast/jboss_gridgain_integration/jboss_gridgain_integration.html", "screencast2", 
        "toolbar=0,status=0,menubar=0,location=0,resizable=1,width=800,height=618");
}

/*
 * Opens up screencast window.
 */
function openJunitIntegrationScreencast() {
    window.open("screencast/junit_integration/junit_integration.html", "screencast3", 
        "toolbar=0,status=0,menubar=0,location=0,resizable=1,width=800,height=618");
}

/*
 * Opens up screencast window.
 */
function openGridGainInstallationScreencast() {
    window.open("screencast/gridgain_installation/gridgain_installation.html", "screencast4",
        "toolbar=0,status=0,menubar=0,location=0,resizable=1,width=800,height=618");
}

/*
 * Opens up screencast window.
 */
function openGridGain30JavaMapReduce() {
    window.open("http://www.youtube.com/user/gridgain?hd=1#p/a/u/0/MXIUc6Tm5uU", "MXIUc6Tm5uU");
}

/*
 * Opens up screencast window.
 */
function openGridGainOverviewReduce() {
    window.open("http://www.youtube.com/user/gridgain?feature=mhum#p/a/u/0/GY8K_bK2aXI", "GY8K_bK2aXI");
}

/*
 *
 */
function web20RowBlue(u, t) {
    var url = typeof u == 'undefined' || new String(u).length == 0 ? document.url : u;
    var title = escape(typeof t == 'undefined' || new String(t).length == 0 ? document.title : t);
    
    web20RowImpl(url, title, 'digg_bw.png', 'furl_bw.png', 'delicious_bw.png', 'reddit_bw.png', 'technorati_bw.png');
}

/*
 *
 */
function web20RowWhite(u, t) {
    var url = typeof u == 'undefined' || new String(u).length == 0 ? document.url : u;
    var title = escape(typeof t == 'undefined' || new String(t).length == 0 ? document.title : t);
    
    web20RowImpl(url, title, 'digg_white.gif', 'furl_white.gif', 'delicious_white.gif', 'reddit_white.gif', 'technorati_white.gif');
}

/*
 *
 */
function isValidEmail(e) {
   return e.value.indexOf(".") > 0 && e.value.indexOf("@") > 0;
}

/*
 *
 */
function isNumeric(e) {
   var validChars = "0123456789";
   var isNumber=true;
   var ch;

   for (i = 0; i < e.value.length && isNumber; i++) { 
      ch = e.value.charAt(i);

      if (validChars.indexOf(ch) == -1) {
         isNumber = false;
      }
   }
   
   return isNumber;   
}

/*
 *
 */
function addCommas(s) {
    s += '';

    var x = s.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';

    var rgx = /(\d+)(\d{3})/;

    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }

    return x1 + x2;
}

/*
 *
 */
function isEmpty(e) {
    return e.value.length == 0 || e.value == null ? true : false;
}

/*
 *
 */
function web20RowImpl(url, title, diggImg, furlImg, deliciousImg, redditImg, technoratiImg) {
    document.write(
        "<a class='img_link' target='digg'" + 
        "    href='http://digg.com/submit?phase=2&url=" + url + "&title=" + title + "'><img title='Submit to Digg' border='0' src='/images/" + diggImg + "'></a>" + 
        "&nbsp;&nbsp;" +                                 
        "<a class='img_link' target='furl'" +  
        "    href='http://www.furl.net/storeIt.jsp?t=" + title + "&u=" + url + "'><img title='Bookmark with Furl' border='0' src='/images/" + furlImg + "'></a>" + 
        "&nbsp;&nbsp;" +                                 
        "<a class='img_link' target='delicious'" +  
        "    href='http://del.icio.us/post?v=4&noui&jump=close&url=" + url + "&title=" + title + "'><img title='Bookmark with Delicious' border='0' src='/images/" + deliciousImg + "'></a>" + 
        "&nbsp;&nbsp;" +                                 
        "<a class='img_link' target='reddit'" +  
        "    href='http://reddit.com/submit?url=" + url + "&title=" + title + "'><img title='Bookmark with Reddit' border='0' src='/images/" + redditImg + "'></a>" +                                
        "&nbsp;&nbsp;" +                                 
        "<a class='img_link' target='technorati'" +  
        "    href='http://technorati.com/faves?add=" + url + "'><img title='Add to Technorati' border='0' src='/images/" + technoratiImg + "'></a>"
    );     
}

/*
 * Adjusts price.
 *
 * @param price Price to adjust.
 */
function formatPrice(price) {
    if (price < 1000)
        price = (price.toFixed(0) / 10).toFixed(0) * 10;
    else if (price < 100000)
        price = (price.toFixed(0) / 100).toFixed(0) * 100;
    else
        price = (price.toFixed(0) / 1000).toFixed(0) * 1000;

    return addCommas((price.toFixed(0) / 10).toFixed(0) * 10)
}

/*
 * Price calculator.
 */
function calculatePrices() {
    var hostsField = document.getElementById("hosts");
    var coresField = document.getElementById("cores");
    var virtField = document.getElementById("virt");

    if (isEmpty(hostsField) || !isNumeric(hostsField)) {
        hostsField.style.borderColor = 'orange';
        hostsField.style.borderStyle = 'solid';
        hostsField.style.borderWidth = '2px';

        return;
    }

    var hosts = hostsField.value;

    if (hosts < 1) {
        hostsField.style.borderColor = 'orange';
        hostsField.style.borderStyle = 'solid';
        hostsField.style.borderWidth = '2px';

        return;
    }

    hostsField.style.borderColor = '#aaa';
    hostsField.style.borderStyle = 'dotted';
    hostsField.style.borderWidth = '1px';

    if (isEmpty(coresField) || !isNumeric(coresField)) {
        coresField.style.borderColor = 'orange';
        coresField.style.borderStyle = 'solid';
        coresField.style.borderWidth = '2px';

        return;
    }

    var coresPerHost = coresField.value;

    if (coresPerHost < 1) {
        coresField.style.borderColor = 'orange';
        coresField.style.borderStyle = 'solid';
        coresField.style.borderWidth = '2px';

        return;
    }

    coresField.style.borderColor = '#aaa';
    coresField.style.borderStyle = 'dotted';
    coresField.style.borderWidth = '1px';

    var totalCores = coresPerHost * hosts;

    document.getElementById("total_cores").innerHTML = addCommas(totalCores);

    // If not enough cores - modify to a minimum to show minimal
    // price in any case.
    if (totalCores < 16) {
        hosts = 2;
        coresPerHost = 8;

        totalCores = 16;
    }

    var price; // Base price.

    if (totalCores < 48)
        price = totalCores * 525 + 9600;
    // Don't publish the price after 128 total cores.
    else if (totalCores < 128)
        price = totalCores * 63.646 + 54826.321;
    else {
        document.getElementById("cmn_price").innerHTML =
            "<a href='mailto:sales@gridgain.com?subject=Community Subscription quote for " + totalCores +
                " cores'>Contact Us</a>";
        document.getElementById("ent_price").innerHTML =
            "<a href='mailto:sales@gridgain.com?subject=Enterprise Subscription quote for " + totalCores +
                " cores'>Contact Us</a>";

        return;
    }

    // Adjust for virtualized discount.
    if (virtField.checked)
        price *= 0.9;

    // Adjust for high density discount.
    if (coresPerHost <= 2)
        price *= 1; // No discount.
    else if (coresPerHost <= 4)
        price *= 0.90;
    else if (coresPerHost <= 8)
        price *= 0.85;
    else if (coresPerHost <= 16)
        price *= 0.80;
    else
        price *= 0.75; // 25% is a max. high density discount.

    var cmnPrice = price * 0.66;
    var entPrice = price;

    var cmnPricePerHost = cmnPrice / hosts;
    var entPricePerHost = entPrice / hosts;

    var cmnPriceStr = formatPrice(cmnPrice);
    var entPriceStr = formatPrice(entPrice);

    var cmnPricePerHostStr = formatPrice(cmnPricePerHost);
    var entPricePerHostStr = formatPrice(entPricePerHost);

    document.getElementById("cmn_price").innerHTML = " $" + cmnPriceStr;
    document.getElementById("ent_price").innerHTML = " $" + entPriceStr;
}

/*
 * Gets latest build date.
 */
function getLatestDate() {
    return 'January 13<sup>th</sup>, 2012';
}

/*
 * Gets latest build version.
 */
function getLatestVersionOnly() {
    return '3.6.0';
}

/*
 * Gets latest build version. 
 */
function getLatestVersion() {
    return 'GridGain ' + getLatestVersionOnly();
}

/*
 * Gets current major version.
 */
function getCurrentMajorVersion() {
    return '3';
}

/*
 * Gets latest build version. 
 */
function getLatestJavadoc() {
    return 'Javadoc';
}

/*
 * Download content. 
 */
function download() {
    document.write(
        "<div style='text-align:center; padding-top: 7px'><img src='/images/downloads_hdr_30.gif'/></div>" +
        "<center>" +
        "<table>" +
        "<tr>" +
            "<td align='center' valign='bottom'><img src='/images/cube_logo_24x29.gif'></td>" +
            "<td align='left' valign='top' style='padding-left: 5px'>" +
            "<span class='news_date'><nobr>" + getLatestDate() + "</nobr></span>" +
            "<br>" +
            "<a title='Downloads' href='/downloads.shtml'><span style='font-size: 11px'>" + getLatestVersion() + "</span></a>" +
            "</td>" +
        "</tr>" +
        "</table>" +
        "</center>" +
        "<p>"
    );
}

/*
 * Twitter feed content.
 */
function twitter() {
    document.write(
        "<center><a href='http://twitter.com/share' class='twitter-share-button' data-count='horizontal' data-via='gridgain'>Tweet</a><script type='text/javascript' src='http://platform.twitter.com/widgets.js'></script></center>" +
        "<ul id='twitter_update_list'><li>Twitter Feed Loading...</li></ul>" +
        "<br><br>"
    );
}

function moreInformation() {
    document.write(
        "<h2>More Information</h2>" +
        "<ul>" +
        "    <li><a href='media/gridgain_white_paper.pdf' target=wp>GridGain - White Paper</a>&nbsp;<img style='vertical-align: baseline;' src='images/pdf_small.png' border='0'></li>" +
        "    <li><a href='media/gridgain_compute_data_integration.pdf' target=wp>Compute and In-Memory Data Grids Integration - White Paper</a>&nbsp;<img style='vertical-align: baseline' src='images/pdf_small.png' border='0'></li>" +
        "    <li><a href='use_cases.html'>Use Cases</a></li>" +
        "    <li><a href='http://jive.gridgain.org' target=forum>Online Forums</a></li>" +
        "    <li><a href='http://www.gridgain.com/javadoc30E/index.html' target=javadoc>Javadoc APIs</a></li>" +
        "    <li><a href='http://www.gridgain.com/book/book.html' target=book>Online Book</a> (under development)</li>" +
        "    <li><a href='http://wiki.gridgain.org' target=wiki>Developers Wiki</a></li>" +
        "</ul>"
    );
}

/*
 * Footer content. 
 */
function footer() {
    document.write(
        "Copyright &copy; 2005-2012 GridGain Systems, Inc. All Rights Reserved." +
        "<br>" +
        "<a class='bottom_menu' href='/legal.html'>Legal Notice</a>&nbsp;&nbsp;|&nbsp;&nbsp;" +
        "<a class='bottom_menu' href='/privacy.html'>Privacy Policy</a>&nbsp;&nbsp;|&nbsp;&nbsp;" +
        "<a class='bottom_menu' href='/contact.html'>Contact Us</a>&nbsp;&nbsp;|&nbsp;&nbsp;" +
        "<a class='bottom_menu' href='/blog.html'>News</a>" +
        "<p>" +
        "<center>" +
            "<a target=github class='img_link' href='https://github.com/gridgain/gridgain'>" +
            "   <img border=0 align=absmiddle src='/images/github_cat_31x28.gif'>" +
            "</a>" +
            "&nbsp;&nbsp;" +
            "<a target=facebook class='img_link' href='http://www.facebook.com/profile.php?id=6458239494'>" +
            "   <img border=0 align=absmiddle src='/images/facebook_small.png'>" +
            "</a>" +
            "&nbsp;&nbsp;" +
            "<a class='img_link' target=meetup href='http://www.meetup.com/GridGain-Bay-Area-Meetup-Group/'>" +
            "   <img border=0 align=absmiddle src='/images/meetup_logo_small.png' alt='Join GridGain Meetup'/>" +
            "</a>" +
            "&nbsp;&nbsp;" +
            "<a class='img_link' target=twitter href='http://www.twitter.com/gridgain'>" +
            "   <img border=0 align=absmiddle src='/images/twitter.gif' alt='Follow GridGain on Twitter'/>" +
            "</a>" +
            "&nbsp;&nbsp;" +
            "<a class='img_link' target=youtube href='http://www.youtube.com/user/gridgain'>" +
            "   <img border=0 align=absmiddle src='/images/youtube_small.png' alt='Follow GridGain on YouTube'/>" +
            "</a>" +
        "</center>"
    );
}

/*
 * Join Us content. 
 */
function joinus() {
    document.write(
        "<div style='text-align:center; padding: 7px 0 5px 0'><img src='/images/join_us_hdr.gif'/></div>" +
        "<center>" +
            "<img width='125' height='25' src='/images/lineup.gif' border=0>" +
            "<p>" +
            "We are  <a title='Join Our Team!' style='font-size: 12px' href='/careers.html'><b>hiring!</b></a>" +
        "</center>" +
        "<p>"
    );
}

/*
 * Join Us content.
 */
function followUs() {
    document.write(
        "<center>" +
            "<div style='color: #369; padding-bottom: 5px; padding-top: 10px'>Follow us:</div>" +
            "<a target=github class='img_link' title='Follow us on Github' href='https://github.com/gridgain/gridgain'><img border=0 align=absmiddle src='/images/github_cat_20x18.gif'></a>" +
            "<img src='/images/spacer.gif' width=7>" +
            "<a target=facebook class='img_link' title='Follow us on Facebook' href='http://www.facebook.com/profile.php?id=6458239494'><img border=0 align=absmiddle src='/images/facebook_small.png'></a>" +
            "<img src='/images/spacer.gif' width=9>" +
            "<a class='img_link' target=twitter title='Follow us on Twitter' href='http://www.twitter.com/gridgain'><img border=0 align=absmiddle src='/images/twitter_small.png' alt='Follow GridGain on Twitter'/></a>" +
            "<img src='/images/spacer.gif' width=9>" +
            "<a class='img_link' target=youtube title='Follow us on YouTube' href='http://www.youtube.com/user/gridgain'><img border=0 align=absmiddle src='/images/youtube_small.png' alt='Follow GridGain on YouTube'/></a>" +
        "</center>" +
        "</center>" +
        "<p>"
    );
}

/*
 * Produces forum search form.
 */
function jiraSearchForm() {
    document.write(
        "<form method='POST' action='http://www.gridgainsystems.com/jira/secure/QuickSearch.jspa' target='jira' style='padding: 1px; margin: 1px'>" + 
            "<img alt='Search JIRA' src='/images/comment.gif' border='0'>" +
            "&nbsp;" +
            "<input class='search_text' type='text' style='color: #ccc' onClick='this.value=\"\"; this.style.color=\"#333\"' name='searchString' id='quickSearchInput'  value=' find...' size='20' maxlength='100'>" + 
            "&nbsp;" +
            "<input title='Search JIRA' class='search_button' name='button' type='submit' value='j i r a'>" + 
        "</form>" 
    );
}

/*
 *
 */
function forumSearchForm() {
    document.write(
        "<form action='http://www.gridgainsystems.com/jiveforums/search.jspa' style='margin: 1px; padding: 1px'>" +
            "<img alt='Search Forums' src='/images/comment.gif' border='0'>" +
            "&nbsp;" +
            "<input class='search_text' type='text' style='color: #ccc' onClick='this.value=\"\"; this.style.color=\"#333\"' name='q'  value=' find...' size='20' maxlength='100'>" + 
            "&nbsp;" +
            "<input title='Search Forums' class='search_button' name='button' type='submit' value='f o r u m'>" + 
        "</form>"
    );
}

/*
 *
 */
function searchForm() {
    document.write(
        "<form method='POST' action='http://www.gridgainsystems.com/wiki/dosearchsite.action' style='margin: 1px; padding: 1px' name='search_form'>" +
            "<input type='hidden' name='quickSearch' value='true'>" +
            "<input type='hidden' name='searchQuery.spaceKey' value='conf_global'>" +
            "<img alt='Search Wiki' src='/images/comment.gif' border='0'>" +
            "&nbsp;" +
            "<input class='search_text' type='text' style='color: #ccc' onClick='this.value=\"\"; this.style.color=\"#333\"' name='searchQuery.queryString' value=' find...' size='20'>" +
            "&nbsp;" +
            "<input title='Search Wiki' class='search_button' name='button' type='submit' value='w i k i'>" +
        "</form>"
    );
}

/*
 * Gets the content of top right navigation.
 */
function topRightNavigation() {
    document.write(
        "<table border=0 cellpadding=0 cellspacing=0>" + 
            "<tr><td style='padding-bottom: 7px' valign='top' align='left'><a style='color: #369' href='contact.html'><b>Contact Us</b></a>&nbsp;<img align='absmiddle' src='/images/envelope.gif' border='0'></td></tr>" +
        "</table>"
    );
}

/*
 * Gets content for developer's blob. 
 */
function developers() {
    document.write(
        "<div style='text-align:center; font-size: 11px; padding-top: 7px'><img src='/images/developers_hdr.gif'/></div>" +
        "<center>" +
        "<table>" +
            "<tr>" +
            "<td align='center'><img src='/images/famfam/cog_bw.png'></td>" +
            "<td width=90' align='left' style='padding-left: 5px'><a title='JIRA, Subversion...' style='font-size: 11px' href='online_resources.html'>Documentation</a></td>" +
            "</tr>" +
//            "<tr>" +
//                "<td align='center'><img src='/images/famfam/page_white_cup_bw.png'></td>" +
//                "<td width='90' align='left' style='padding-left: 5px'><a title='View Javadoc' style='font-size: 11px' target='javadoc' href='http://www.gridgain.com/javadoc30E/index.html'>" + getLatestJavadoc() + "</a></td>" +
//            "</tr>" +
            "<tr>" +
                "<td align='center'><img src='/images/famfam/television_bw.png'></td>" +
                "<td width=90' align='left' style='padding-left: 5px'><a title='Examples' style='font-size: 11px' href='https://github.com/gridgain/gridgain/tree/master/examples'>Examples</a></td>" +
            "</tr>" +
//            "<tr>" +
//                "<td align='center'><img src='/images/famfam/book_open_bw.png'></td>" +
//                "<td width=90' align='left' style='padding-left: 5px'><a target='wiki' style='font-size: 11px' href='http://www.gridgain.com/book/book.html' title='Real Time Big Data Processing with GridGain'>Book</a></td>" +
//            "</tr>" +
            "<tr>" +
                "<td align='center'><img src='/images/famfam/comments_bw.png'></td>" +
                "<td width=90' align='left' style='padding-left: 5px'><a target='jive' style='font-size: 11px' href='http://jive.gridgain.org' title='Online Forums'>Online Forum</a></td>" +
            "</tr>" +
        "</table>" +
        "</center>" +
        "<p>"
    );
}

