/* global variables */
var g_PC_ID = '';
var g_sms_ID = '';
var g_label_ID = '';
var g_timeout_ID;
var g_txtField_obj = null;
var g_form = null
var g_suggest_cache = new Array();
var g_suggest_xmlhttp = null;
var g_keyCode = null;
var g_listLength = 0;
var g_listID = -1;

function createAJAX() {
    var x=false;
    try{
        x = new ActiveXObject("Msxml2.XMLHTTP");
    }catch(e){
        try{
            x = new ActiveXObject("Microsoft.XMLHTTP");
        }catch(ee){
            x=false;
        }
    }

    if (!x && typeof XMLHttpRequest!='undefined'){
        try {
            x = new XMLHttpRequest();
        }catch(e) {
            x = false;
        }
    }
    return x;
}

function similar_mouseover(img_name, img_url, price) {
    var t = document.getElementById(img_name);
    alt = '';

    if(!img_url) {
        img_url = "no_image.jpg";
        alt = 'alt="No image found"';
    }

    t.innerHTML = '<img src="' + img_url + '" ' + alt + ' border="0" /><br /><b>' + price + '</b>';
}

function similar_mouseout(img_name) {
    var t = document.getElementById(img_name);
    t.innerHTML = '';
}

// iframe info
function displayiFrame(div_name, textspan_name, url) {
    var d = document.getElementById(div_name);
    var t = document.getElementById(textspan_name);
    var h = document.getElementById("hidden_iframe");

    if(d.style.display != "block") { // user clicked 'View'
        d.style.display = "block";
        t.innerHTML = "Hide";

        // d.completeDownload is self-created.
        if(!d.completeDownload) {  // never loaded before or incomplete
            d.innerHTML = '<img src="loading.gif" />';

            g_PC_ID = div_name;
            h.callback_func = displayiFrame_callback;

            h.src = url;
        }
    }else {
        d.style.display = "none";
        t.innerHTML = "View";
    }

    return false;
}

function displayiFrame_callback(doc) {
    var d = document.getElementById(g_PC_ID);

    d.innerHTML = doc.body.innerHTML;
    d.completeDownload = true;
}

function sms(f) {
    var ajax = createAJAX();

    if(ajax && f.number && f.asin && f.result_id) {
        var phone = f.number.value.replace(/^\s+/, '').replace(/\s+$/, '');
        var d = document.getElementById(f.result_id.value);

        if(!phone.match(/^\d{10}$/)) {
            d.innerHTML = "The mobile number is invalid. Please try again.";
            d.style.display="block";
        }else {
            d.style.display="block";
            d.innerHTML = "Please wait...";

            // &random to prevent caching of the page.
            url = "/sms?ajax=1&asin=" + urlencode(f.asin.value) + "&phone=" + urlencode(f.number.value)  + "&random=" + Math.random();

            ajax.open("GET",url,true);
            ajax.onreadystatechange=function(){
                if(ajax.readyState==4){d.innerHTML = ajax.responseText;}
            }
            ajax.send(null);
        }
    }else {
        sms_iframe(f);
    }
    return false;
}

function sms_iframe(f) {
    if(f.number && f.asin && f.result_id) {
        var phone = f.number.value.replace(/^\s+/, '').replace(/\s+$/, '');
        var d = document.getElementById(f.result_id.value);

        if(!phone.match(/^\d{10}$/)) {
            d.innerHTML = "The mobile number is invalid. Please try again.";
            d.style.display="block";
        }else {
            d.style.display="block";
            d.innerHTML = "Please wait...";

            var h = document.getElementById("hidden_iframe");

            g_sms_ID = f.result_id.value;

            h.callback_func = null_callback;
            h.src = "sms?asin=" + urlencode(f.asin.value) + "&phone=" + urlencode(f.number.value) + "&random=" + Math.random();
        }
    }

    return false;
}

function email(f) {
    var ajax = createAJAX();

    if(ajax && f.address && f.asin && f.result_id) {
        var d = document.getElementById(f.result_id.value);
        d.style.display="block";
        d.innerHTML = "Please wait...";

        url = "/email?ajax=1&asin=" + urlencode(f.asin.value) + "&email=" + urlencode(f.address.value) + "&random=" + Math.random();

        ajax.open("GET",url,true);
        ajax.onreadystatechange=function(){
            if(ajax.readyState==4){d.innerHTML = ajax.responseText;}
        }

        ajax.send(null);
    }else {
        email_iframe(f);
    }

    return false;
}




// fall back on iframes if AJAX doesn't work
function email_iframe(f) {
    if(f.address && f.asin && f.result_id) {
        var d = document.getElementById(f.result_id.value);
        d.style.display="block";
        d.innerHTML = "Please wait...";

        var h = document.getElementById("hidden_iframe");

        g_sms_ID = f.result_id.value;

        h.callback_func = null_callback;
        h.src = "email?asin=" + urlencode(f.asin.value) + "&email=" + urlencode(f.address.value)  + "&random=" + Math.random();
    }

    return false;
}


function price_alert(f) {
    var ajax = createAJAX();

    if(ajax && f.asin && f.result_id) {
        var budget = trim(f.budget.value);
        var d = document.getElementById(f.result_id.value);

        if(!budget.match(/^\$?\d+\.?\d*$/)) {
            d.innerHTML = "Please enter a valid value for your budget.";
            d.style.display="block";
        }else {
            d.style.display="block";
            d.innerHTML = "Please wait...";

            var pricetype = '';

            if(f.pricetype) {
                for(var i = 0; i < f.pricetype.length; i++) {
                    if(f.pricetype[i].checked) {
                        pricetype = f.pricetype[i].value;
                        break;
                    }
                }
            }else {
                pricetype = f.defaultpricetype.value;
            }

            // &random to prevent caching of the page.
            url = "/pricealert?ajax=1&asin=" + urlencode(f.asin.value) + "&budget=" + urlencode(budget) + "&email=" + urlencode(f.email.value) + "&pricetype=" + urlencode(pricetype) + "&random=" + Math.random();

            ajax.open("GET",url,true);
            ajax.onreadystatechange=function(){
                if(ajax.readyState==4){d.innerHTML = ajax.responseText;}
            }
            ajax.send(null);
        }
    }else {
        price_alert_iframe(f);
    }
    return false;
}

function price_alert_iframe(f) {
    if(f.asin && f.result_id) {
        var budget = trim(f.budget.value);
        var d = document.getElementById(f.result_id.value);

        if(!budget.match(/^\$?\d+\.?\d*$/)) {
            d.innerHTML = "Please enter a valid value for your budget.";
            d.style.display="block";
        }else {
            d.style.display="block";
            d.innerHTML = "Please wait...";

            var h = document.getElementById("hidden_iframe");

            g_sms_ID = f.result_id.value;

            h.callback_func = null_callback;

            var pricetype = '';

            if(f.pricetype) {
                for(var i = 0; i < f.pricetype.length; i++) {
                    if(f.pricetype[i].checked) {
                        pricetype = f.pricetype[i].value;
                        break;
                    }
                }
            }else {
                pricetype = f.defaultpricetype.value;
            }

            h.src = "pricealert?asin=" + urlencode(f.asin.value) + "&budget=" + urlencode(budget) + "&email=" + urlencode(f.email.value) + "&pricetype=" + urlencode(pricetype) + "&random=" + Math.random();
        }
    }

    return false;
}

//  called from <body onload="..."> in iframe content.
function exportBuffer() {
    var h = document.getElementById("hidden_iframe");
//    h.callback_func(window.frames['hidden_iframe'].document);
    if(h.callback_func) {
        h.callback_func(getIFrame('hidden_iframe'));
    }
}

function null_callback(doc) {
    var d = document.getElementById(g_sms_ID);

    d.style.display="block";
    d.innerHTML = doc.body.innerHTML;
}

function displayEmbedded(div_name) {
    var d = document.getElementById(div_name);

    if(d.style.display != "block") { // user clicked 'View'
        d.style.display = "block";
    }else {
        d.style.display = "none";
    }

    return false;
}

function displayProductExpand(div_name, textspan_name) {
    var d = document.getElementById(div_name);
    var t = document.getElementById(textspan_name);

    if(d.style.display != "block") { // user clicked 'View'
        t.innerHTML = "Hide details";
        d.style.display = "block";
    }else {
        t.innerHTML = "More details";
        d.style.display = "none";
    }

    return false;
}

function categoryView(category_name) {
    var d, t, c, i;

    t = document.getElementById('name_all');
    i = 1;

    while(true) {
        d = document.getElementById('item_' + i);

        if(d) {
            i++;
            c = document.getElementById('name_' + d.className);

            // bold, unbold category
            if(category_name == 'all') {
                t.className = "txt_bold";
                c.className = "txt_no_bold";
            }else if(category_name == d.className) {
                t.className = "txt_no_bold";
                c.className = "txt_bold";
            }else if(category_name != d.className) {
                t.className = "txt_no_bold";
                c.className = "txt_no_bold";
            }


            // show and hide items
            if(category_name == 'all' || d.className == category_name) {
                d.style.display = "block";
            }else {
                d.style.display = "none";
            }
        }else {
            break;
        }
    }
    return false;
}

function moreReviews(d, url) {
    var h = document.getElementById("hidden_iframe");

    d.innerHTML = '<img src="loading.gif" />';
    g_PC_ID = d.id;

    h.callback_func = moreReviews_callback;
    h.src = url;

    return false;
}

function moreReviews_callback(doc) {
    var d = document.getElementById(g_PC_ID);

    d.innerHTML = doc.body.innerHTML;
}

function labels(f) {
    if(f.asin && f.result_id && f.l) {
        var h = document.getElementById("hidden_iframe");

        g_label_ID = f.result_id.value;
        h.callback_func = labels_callback;
        rm = f.r ? "&r=1" : '';

        h.src = "labels?asin=" + f.asin.value + "&label_id=" + f.l.value + rm;
    }

    return false;
}

function labels_callback(doc) {
    var d = document.getElementById(g_label_ID);
    d.innerHTML = doc.body.innerHTML;
}

function removeLabel(chk_id) {
    var d = document.getElementById("changelabels_form");
    var e = document.getElementById("pub_chkbox_" + chk_id);
    var label = "label_" + chk_id;
    var t = eval("d." + label);

    d = document.getElementById("rm_label_" + chk_id);

    if(t.disabled) {
        t.disabled = false;
        d.style.visibility="visible";
        e.style.visibility="visible";
    }else {
        t.disabled = true;
        d.style.visibility="hidden";
        e.style.visibility="hidden";
        mod_closeColorPalette();
    }
}

function mod_colorPicker(id) {
    var c = document.getElementById("colorpalette");
    var d = document.getElementById("color_choices_" + id);
    var e = document.getElementById("changelabels_form");

    if(e.selected_label.value != "") {
        mod_closeColorPalette();
    }

    c.style.display="block";
    d.style.visibility="visible";
    e.selected_label.value=id;
}

function mod_closeColorPalette() {
    var c = document.getElementById("colorpalette");
    var e = document.getElementById("changelabels_form");
    var id = e.selected_label.value;

    if(id == "") {
        return;
    }
    var d = document.getElementById("color_choices_" + id);

    c.style.display="none";
    d.style.visibility="hidden";
    e.selected_label.value="";
}

// show color as mouse hovers over color palette
function mod_sc(color) {
    var e = document.getElementById("changelabels_form");
    var id = e.selected_label.value;
    var d = document.getElementById("color_choices_" + id);
    d.style.background=color;
}

// selects the color from sc().
function mod_cc(color) {
    var d = document.getElementById("changelabels_form");
    var id = d.selected_label.value;

    // the input value
    var t = eval("d.color_" + id);
    t.value=color;

    // the displayed color
    var e = document.getElementById("label_color_" + id);
    e.style.background=color;
}

// set back to original color
function origColor() {
    var d = document.getElementById("changelabels_form");
    var id = d.selected_label.value;

    // original value
    var t = eval("d.orig_color_" + id);
    var origColor = t.value;

    // set input value
    t = eval("d.color_" + id);
    t.value = origColor;

    // set displayed color
    var e = document.getElementById("label_color_" + id);
    e.style.background=origColor;
}

function add_colorPicker(id) {
    var c = document.getElementById("add_colorpalette");
    var d = document.getElementById("add_color_choices_" + id);
    var e = document.getElementById("addlabels_form");
    var f = document.getElementById("add_label_color_" + id);

    c.style.display="block";
    d.style.visibility="visible";
    e.add_selected_label.value = id;

    t = eval("e.add_color_" + id);
    f.style.background = t.value;
}

function add_closeColorPalette() {
    var c = document.getElementById("add_colorpalette");
    var e = document.getElementById("addlabels_form");
    var id = e.add_selected_label.value;

    if(id == "") {
        return;
    }
    var d = document.getElementById("add_color_choices_" + id);

    c.style.display="none";
    d.style.visibility="hidden";
    e.add_selected_label.value="";
}

// show color as mouse hovers over color palette
function add_sc(color) {
    var e = document.getElementById("addlabels_form");
    var id = e.add_selected_label.value;
    var d = document.getElementById("add_color_choices_" + id);
    d.style.background=color;
}

// selects the color from add_sc().
function add_cc(color) {
    var d = document.getElementById("addlabels_form");
    var id = d.add_selected_label.value;

    // the input value
    var t = eval("d.add_color_" + id);
    t.value=color;

    // the displayed color
    var e = document.getElementById("add_label_color_" + id);
    e.style.background=color;
}

function clearSearchHistory() {
    var decision = confirm("By choosing OK, your ENTIRE search history will be permanently deleted.\n\nAre you sure you want to proceed?");

    if(!decision) {
        return false;
    }

    var ajax = createAJAX();

    if(ajax) {
        var d = document.getElementById("savedsearches").innerHTML = '';

        url = "/sehistory?ajax=1&random=" + Math.random();
        ajax.open("GET",url,true);
        ajax.onreadystatechange=function(){
            // do nothing
        }
        ajax.send(null);
    }else {
        clearSearchHistory_iframe();
    }

    return false;
}

function clearSearchHistory_iframe() {
    var d = document.getElementById("savedsearches").innerHTML = '';
    var h = document.getElementById("hidden_iframe");

    h.callback_func = null; // to avoid interfering with other functions that use iframe too.
    h.src = "sehistory?random=" + Math.random() ;

    return false;
}

function showSearchHistory(page) {
    var h = document.getElementById("hidden_iframe");

    h.callback_func = showSearchHistory_callback;
    h.src = "sehistory/show/" + page;

    return false;
}

function showSearchHistory_callback(doc) {
    var d = document.getElementById("search_history");
    d.innerHTML = doc.body.innerHTML;
}

//http://en.wikipedia.org/wiki/User_agent
function permLinkText(obj) {
    obj.T_FONTSIZE='100%';
    obj.T_BGCOLOR='white';
    obj.T_SHADOWWIDTH=5;
    obj.T_SHADOWCOLOR='#cccccc';
    obj.T_TITLE = obj.title;

    var agt=navigator.userAgent;
    var x;

    if(agt) {
        if(agt.search(/opera/i) != -1) {
            x = 'Bookmark page';
        }else if(agt.search(/safari/i) != -1) {
            x = 'Add Bookmarks';
        }else if(agt.search(/gecko/i) != -1) { // firefox, netscape, mozilla
            x = 'Bookmark This Link';
        }else if(agt.search(/msie/i) != -1) {
            x = 'Add to Favorites';
        }else {
            x = 'Bookmark This Link';
        }
    }else {
        x = 'Add to Favorites';
    }

    return "To bookmark this product, right click on 'Bookmark this product' and select '" + x + "'.";
}

function relatedSuggestionsText(obj, id) {
    obj.T_STICKY=true;
    obj.T_FONTSIZE='100%';
    obj.T_BGCOLOR='white';
    obj.T_SHADOWWIDTH=5;
    obj.T_SHADOWCOLOR='#cccccc';
    return document.getElementById(id).innerHTML;
}

function moreArAuInfo(obj, name_urlencode) {
    obj.T_STICKY=true;
    obj.T_FONTSIZE='100%';
    obj.T_BGCOLOR='white';
    obj.T_SHADOWWIDTH=5;
    obj.T_SHADOWCOLOR='#cccccc';
    obj.T_ABOVE=true;
    obj.T_TITLE = obj.title;

    imgURL_a9 = 'http://a9.com/' + name_urlencode + '?a=simage';
    imgURL_a9_win = '<a href="' + imgURL_a9 + '" target="_blank" title="Open in new window"><img src="new_win.gif" /></a>'
    imgURL_yh = 'http://images.search.yahoo.com/search/images?p=' + name_urlencode;
    imgURL_yh_win = '<a href="' + imgURL_yh + '" target="_blank" title="Open in new window"><img src="new_win.gif" /></a>'
    whoisURL_a9 = 'http://a9.com/' + name_urlencode + '?a=swikipedia';
    whoisURL_a9_win = '<a href="' + whoisURL_a9 + '" target="_blank" title="Open in new window"><img src="new_win.gif" /></a>';
    newsURL_goog = 'http://news.google.com/news?q=' + name_urlencode;
    newsURL_goog_win = '<a href="' + newsURL_goog + '" target="_blank" title="Open in new window"><img src="new_win.gif" /></a>';

    img = 'Find pictures from <a href="'+ imgURL_a9 + '">A9</a>' /*&nbsp;' + imgURL_a9_win */+ ' or ' + '<a href="' + imgURL_yh + '">Yahoo!</a>';//&nbsp;' + imgURL_yh_win;
    whois = '<a href="' + whoisURL_a9 + '">Who is</a> ' + /*whoisURL_a9_win + ' ' +*/ obj.title + '?';
    news = '<a href="' + newsURL_goog + '">Latest news</a>' /*+newsURL_goog_win*/ + ' about ' + obj.title;

    return '<ul><li>' + whois + '</li><li>' + img + '</li><li>' + news + '</li></ul>';
}

function whyUseA9(obj) {
    obj.T_STICKY=true;
    obj.T_FONTSIZE='100%';
    obj.T_BGCOLOR='white';
    obj.T_SHADOWWIDTH=5;
    obj.T_SHADOWCOLOR='#cccccc';
    obj.T_TITLE = "Because A9 Saves You Money!";

    msg = "Amazon.com gives an <b>additional discount</b> of 1.57% on most purchases for regular users of A9.<br />";
    msg += '<a href="http://www.amazon.com/gp/xs/sharethepi.html">Details here</a>';

    return msg;
}

function dvdMore(obj) {
    obj.T_STICKY=true;
    obj.T_FONTSIZE='100%';
    obj.T_BGCOLOR='white';
    obj.T_SHADOWWIDTH=5;
    obj.T_SHADOWCOLOR='#cccccc';
    obj.T_TITLE = "Learn More";

    video = obj.title;
    amznTrailers = '&bull; Amazon.com has upcoming <a href="http://www.amazon.com/exec/obidos/redirect?tag=tictap-20&creative=9325&camp=1789&link_code=ur2&path=tg/browse/-/565316">movie trailers</a>!';
    yahooVideo = '&bull; Find video clips at <a href="http://video.search.yahoo.com/search/video?p=' + video +'">Yahoo!</a>';
    wikipedia = '&bull; <a href="http://a9.com/' + video + '?a=swikipedia">Wikipedia</a> search';
    imdb = '&bull; <a href="http://a9.com/' + video + '?a=smovie">Internet Movie Database</a> search';

    return yahooVideo + "<br />" + imdb + "<br />" + wikipedia + "<br />" + amznTrailers;
}

function highlightReview(word, color, total) {
    var d;
    var t;
    var regex_noColor = new RegExp(word, "gi");
    var regex_Color = new RegExp("<span .+?>" + word + "</span>", "gi");

    for(var i = 1; i <= total; i++) {
        d = document.getElementById('review_' + i);
        t = d.innerHTML;

        if(t.search(regex_Color) == -1) { // color not turned on yet.
            d.innerHTML = t.replace(regex_noColor, '<span style="background-color:' + color + '">' + word + '</span>');
        }else{ // color already turned on, turn it off now.
            d.innerHTML = t.replace(regex_Color, word);
        }
    }
}

function getIFrame(frame_name)
{
    if(window.frames[frame_name].document) {
        return window.frames[frame_name].document;
    }else {
        var oIframe = document.getElementById(frame_name);
        var oDoc = (oIframe.contentWindow || oIframe.contentDocument);

        return (oDoc.document) ? oDoc.document : oDoc;
    }
}

function loadSuggest() {
    if(g_suggest_xmlhttp && g_suggest_xmlhttp.readyState != 0){
        g_suggest_xmlhttp.abort();
    }

    g_suggest_xmlhttp = createAJAX();

    if(!g_suggest_xmlhttp) {
        return;
    }

    if(g_suggest_cache[niceWord(g_txtField_obj.value)] != undefined) {
        parseSuggest(g_suggest_cache[niceWord(g_txtField_obj.value)], true);
    }else {
        var url = "/suggest?k=" + escapeURI(g_txtField_obj.value) + "&random=" + Math.random();

        g_suggest_xmlhttp.open("GET",url,true);
        g_suggest_xmlhttp.onreadystatechange=function(){
            if(g_suggest_xmlhttp.readyState==4){ parseSuggest(g_suggest_xmlhttp.responseText, false);}
        }
        g_suggest_xmlhttp.send(null);
    }
}

function parseSuggest(t, isCache) {
    try {
        var s_bag = isCache ? t : eval(t);
        var bag = new Array();
        var t ='';
        var j = 0;
        for(var i = 0; i < s_bag.length; i++) {
            if(s_bag[i].search(/download|lyric/i) == -1) {
                bag.push(s_bag[i]);

                mout = ' onmouseout="suggest_mouseout(' + j + ');" ';
                mdown = ' onmousedown="suggest_mousedown(' + j + ');" ';
                mover = ' onmouseover="suggest_mouseover(' + j + ');" ';

                t += '<div id="sdiv_' + j + '"' + mout + mdown + mover + 'style="text-align:left;padding-left:0.5em;padding-right:0.5em">&bull; ' + s_bag[i] + '</div>';

                j++;
            }
        }

        if(bag.length == 0) {
            return null;
        }else {
            g_listLength = j;

            if(!isCache) {
                g_suggest_cache[niceWord(g_txtField_obj.value)] = bag;
            }

            displaySuggest(t);
        }
    }catch(e) {
        return null; // eval() failed.
    }
}

function displaySuggest(t) {
    var d = document.getElementById('suggest_block');
    d.style.position="absolute";
    d.style.left="250px";
    d.style.left="250px";
    d.style.backgroundColor="white";
    d.style.border="1px blue solid";
    d.innerHTML = t;
    d.style.display="block";

    g_txtField_obj.focus(); // IE loses focus
}

function fireSuggest(e, form_obj) {
    if(!form_obj || !form_obj.keywords.value || trim(form_obj.keywords.value) == '') {
        return;
    }

    clearTimeout(g_timeout_ID);
    g_txtField_obj = form_obj.keywords;
    g_form = form_obj;
    g_keyCode = getKey(e);

/*    if(g_keyCode == 13 || g_keyCode == 3) { // enter. 3 is for Mac.
        suggest_mousedown(g_listID);
        return false;
    }

    if(g_listLength > 0) {
        if(g_keyCode == 40) { //down arrow
            keyDown_pressed();
            return false;
        }else if(g_keyCode == 38) { //up arrow
            keyUp_pressed();
            return false;
        }
    }
*/
    g_timeout_ID = setTimeout("loadSuggest()", 1000);

    return true;
}


// down arrow
function keyDown_pressed() {
    if(g_listID == (g_listLength - 1)) {
        // was at last item, so loop to first item.
        suggest_mouseover(0);
    }else if(g_listID < 0) {
        // was at input element, so move to first item.
        suggest_mouseover(0);
    }else {
        // move to next item
        suggest_mouseover(g_listID + 1);
    }
}

// up arrow
function keyUp_pressed() {
    if(g_listID == 0) {
        // was at first item, so loop to last item.
        suggest_mouseover(g_listLength - 1);
    }else if(g_listID < 0) {
        // was at input element, so move to last item.
        suggest_mouseover(g_listLength - 1);
    }else {
        // move to next item
        suggest_mouseover(g_listID - 1);
    }
}

function suggest_mouseover(id) {
    if(g_listID > -1) {
        suggest_mouseout(g_listID);
    }

    var d = document.getElementById('sdiv_' + id);
    d.style.backgroundColor="yellow";
    d.style.cursor="pointer";

    g_listID = id;
}

function suggest_mouseout(id) {
    var d = document.getElementById('sdiv_' + id);
    d.style.backgroundColor="white";
    d.style.cursor="default";
}

function suggest_mousedown(div_val) {
    if(g_suggest_cache[niceWord(g_txtField_obj.value)] != undefined) {
        var bag = g_suggest_cache[niceWord(g_txtField_obj.value)];

        if(bag[div_val] != undefined) {
            g_txtField_obj.value = bag[div_val];

            g_form.submit();
        }
    }
}

function suggestOff() {
    var d = document.getElementById('suggest_block');
    d.style.display="none";
    resetListValues();
}

function resetListValues() {
    g_listLength = 0;
    g_listID = -1;
}

function getKey(e) {
    var code;
    if (!e) {
        var e = window.event;
    }

    if (e.keyCode) {
        code = e.keyCode;
    }else if(e.which) {
        code = e.which;
    }

    return code;
}

function escapeURI(k){
    if(encodeURIComponent) {
        try {
            return encodeURIComponent(k);
        }catch (e) {
            return '';
        }
    }else if(escape) {
        return escape(k);
    }

    return '';
}

function trim(word) {
    return word.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

function niceWord(word) {
    return escapeURI(trim(word.toLowerCase()));
}

function addWatchlist(asin) {
    var ajax = createAJAX();

    if(ajax) {
        url = "/watchlist/add/" + asin + "?random=" + Math.random();

        ajax.open("GET",url,true);
        ajax.onreadystatechange=function(){
            if(ajax.readyState==4){
                showWatchlistAdded(asin);
            }
        }
        ajax.send(null);
    }else {
        addWatchlist_iframe(asin);
    }
}

function showWatchlistAdded(asin) {
    var d = document.getElementById('watchlist_' + asin);
    d.style.display="inline";
}

function addWatchlist_iframe(asin) {
    var h = document.getElementById("hidden_iframe");

    h.src = "watchlist/add/" + asin + "?random=" + Math.random();

    // since there are no return values, we pause a while to give illusion of work.
    // then show the Added message.
    setTimeout("showWatchlistAdded('" + asin + "');", 1000);
}

function wl_chk(asin) {
    var d = document.getElementById('wltd_' + asin);

    // cannot use if(d.style.backgroundColor == "#e5ecf9")
    // bcos firefox uses rgb(..) internally.
    if(d.isSelected) {
        d.style.backgroundColor = "";
        d.isSelected = false;
    }else {
        d.style.backgroundColor = "#e5ecc9";
        d.isSelected = true;
    }

    return true;
}

function wl_selAll() {
    if(document.wl_form.elements['chk[]']) {
        var c = document.wl_form.elements['chk[]'];

        var len = c.length;

        if(!len) { // 1 item only.
            if(!c.checked) {
                c.checked = true;
                wl_chk(c.value);
            }
        }else {
            for(var i = 0; i < len; i++) {
                if(!c[i].checked) {
                    c[i].checked = true;
                    wl_chk(c[i].value);
                }
            }
        }
    }
}

function wl_unselAll() {
    if(document.wl_form.elements['chk[]']) {
        var c = document.wl_form.elements['chk[]'];

        var len = c.length;

        if(!len) { // 1 item only.
            if(c.checked) {
                c.checked = false;
                wl_chk(c.value);
            }
        }else {
            for(var i = 0; i < len; i++) {
                if(c[i].checked) {
                    c[i].checked = false;
                    wl_chk(c[i].value);
                }
            }
        }
    }
}

function wl_remSelected() {
    document.wl_form.action = "watchlist/del";
    document.wl_form.submit();
}


function changeVarImg() {
    f = document.variation_form;
    if(f) {
        var len = f.keywords.length;
        for(var i = 0; i < len; i++) {
            if(f.keywords.options[i].selected) {
                var d = document.getElementById('variation_img');
                // var_img_bag in template
                d.src=var_img_bag[i+1];
                return false;
            }
        }
    }
    return false;
}

function urlencode(k){
    if(encodeURIComponent) {
        try {
            return encodeURIComponent(k);
        }catch (e) {
            return '';
        }
    }else if(escape) {
        return escape(k);
    }

    return '';
}

function urlunencode(k){
    if(decodeURIComponent) {
        try {
            return decodeURIComponent(k);
        }catch (e) {
            return '';
        }
    }else if(unescape) {
        return unescape(k);
    }

    return '';
}

function isFirefox() {
    if ((typeof window.sidebar == "object") && (typeof window.sidebar.addSearchEngine == "function"))  {
        document.getElementById('firefox_plugin').style.display="block";
        return true;
    }else {
        return false;
    }
}

/* firefox plugin */
function addEngine(name,ext,cat,type){
    if ((typeof window.sidebar == "object") && (typeof window.sidebar.addSearchEngine == "function"))  {
        window.sidebar.addSearchEngine("http://www.tictap.com/downloads/"+name+".src","http://www.tictap.com/downloads/"+name+"."+ext,name,cat);
    }
}

function cc(price) {
    var exchange = getCookie('exchange_rate');
    if(!exchange) {
        return;
    }else {
        currency_abbrev = exchange.match(/^([^0-9\.]+)/);
        if(currency_abbrev) {
            currency_abbrev = currency_abbrev[0];
        }

        exchange = onlyMoneyValue(exchange);
    }

    price = onlyMoneyValue(price);

    if(!price || !exchange) {
        return;
    }else {
        price *= exchange;
        price = roundToDecimalPlaces(price, 2);
        if(price) {
            document.write(currency_abbrev + price);
        }
    }
}

function convertCurrency(){
    var exchange = document.currency_form.exchangerate.value;
    var currency_abbrev = '';

    setCookie('exchange_rate', exchange.slice(0, 10), null, '/');

    if(exchange) {
        currency_abbrev = exchange.match(/^([^0-9\.]+)/);
        if(currency_abbrev) {
            currency_abbrev = currency_abbrev[0];
        }

        exchange = onlyMoneyValue(exchange);
    }

    if(!exchange) {
        return false;
    }

    var d_list_usd = document.getElementById('list_usd');
    var d_amazon_usd = document.getElementById('amazon_usd');
    var d_used_usd = document.getElementById('used_usd');
    var d_third_usd = document.getElementById('third_usd');
    var temp = 0;

    if(d_list_usd) {
        temp = onlyMoneyValue(d_list_usd.innerHTML);
        temp *= exchange;
        document.getElementById('list_currency').innerHTML = temp ? currency_abbrev + roundToDecimalPlaces(temp,2) : '';
    }

    if(d_amazon_usd) {
        temp = onlyMoneyValue(d_amazon_usd.innerHTML);
        temp *= exchange;
        document.getElementById('amazon_currency').innerHTML = temp ? currency_abbrev + roundToDecimalPlaces(temp,2) : '';
    }

    if(d_used_usd) {
        temp = onlyMoneyValue(d_used_usd.innerHTML);
        temp *= exchange;
        document.getElementById('used_currency').innerHTML = temp ? currency_abbrev + roundToDecimalPlaces(temp,2) : '';
    }

    if(d_third_usd) {
        temp = onlyMoneyValue(d_third_usd.innerHTML);
        temp *= exchange;
        document.getElementById('third_currency').innerHTML = temp ? currency_abbrev + roundToDecimalPlaces(temp,2) : '';
    }
}

function onlyMoneyValue(v) {
    v = v.replace(/[^0-9\.]/g, '');
    return v;
}

/* http://www.webreference.com/js/column8/functions.html */
function setCookie(name, value, expires, path, domain, secure) {
    var nextyear = new Date();
    nextyear.setFullYear(nextyear.getFullYear() + 5); // 5 years
    expires = expires ? expires.toGMTString() : nextyear.toGMTString();

    var curCookie = name + "=" + urlencode(value) +
      "; expires=" +  expires +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");

    document.cookie = curCookie;
}


function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);

    if(begin == -1) {
        begin = dc.indexOf(prefix);

        if (begin != 0) {
            return null;
        }
    }else {
        begin += 2;
    }

    var end = document.cookie.indexOf(";", begin);

    if(end == -1) {
        end = dc.length;
    }

    return urlunencode(dc.substring(begin + prefix.length, end));
}


function deleteCookie(name, path, domain) {
    if(getCookie(name)) {
        document.cookie = name + "=" +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

function roundToDecimalPlaces(number, x) {
    return Math.round(number * Math.pow(10, x))/Math.pow(10, x);
}

function shipOption() {
    var d = document.getElementById('show_shipper_option_dummy');
    var t = document.getElementById('show_shipper_option');
    if(d && t) {
        if(d.style.display == 'block') {
            d.style.display = 'none';
            t.innerHTML = 'Show me all sellers';
            internationalShippersOnly();
        }else {
            d.style.display = 'block';
            t.innerHTML = 'Show me just the sellers with international shipping';
            allShippers();
        }
    }
}

function internationalShippersOnly() {
    var d = null;
    for(var i = 1; i <=10; i++) {
        d = document.getElementById('no_ship_international_' + i);
        if(d) {
            d.style.display ='none';
        }
    }
}

function allShippers() {
    var d = null;
    for(var i = 1; i <=10; i++) {
        d = document.getElementById('no_ship_international_' + i);
        if(d) {
            d.style.display ='';
        }
    }
}