//********************************
// gallery functions
//********************************
var CPGallery = new function() {
    var oJQBtnPrev = null;
    var sBtnPrevPic = "";
    var sBtnPrevPicDisable = "";
    var oJQBtnNext = null;
    var sBtnNextPic = "";
    var sBtnNextPicDisable = "";
    var oJQUL = null;

    var bCanPrev = false;
    var bCanNext = false;
    var iCurrentIdx = 0;   //current idx of visible item(0 base)
    var iMaxColNum = 0;     //max colum can visible in the container

    var getDiablePicName = function(sSrcEnable) {
        var sRtn = "";
        if (sSrcEnable) {
            var iPos = sSrcEnable.lastIndexOf(".");
            if (iPos != -1) {
                sRtn = sSrcEnable.substring(0, iPos) + "Disable" + sSrcEnable.substr(iPos);
            }
        }
        return sRtn;
    };

    var updateBtnState = function() {
        bCanNext = oJQUL.children("li:visible").length > iMaxColNum;
        bCanPrev = iCurrentIdx > 0;

        oJQBtnPrev.attr("src", bCanPrev ? sBtnPrevPic : sBtnPrevPicDisable);
        oJQBtnNext.attr("src", bCanNext ? sBtnNextPic : sBtnNextPicDisable);
    };

    this.onPrev = function() {
        if (bCanPrev) {
            oJQUL.children("li:eq(" + (--iCurrentIdx) + ")").fadeIn("fast", updateBtnState);
        }
    };

    this.onNext = function() {
        if (bCanNext) {
            oJQUL.children("li:eq(" + (iCurrentIdx++) + ")").fadeOut("fast", updateBtnState);
        }
    };

    this.init = function(oUL, oPrev, oNext, iMaxCol) {
        oJQBtnPrev = oPrev;
        oJQBtnNext = oNext;
        oJQUL = oUL;
        iMaxColNum = iMaxCol;

        if (oJQBtnPrev && oJQBtnNext && oJQUL) {
            sBtnPrevPic = oJQBtnPrev.attr("src");
            sBtnPrevPicDisable = getDiablePicName(sBtnPrevPic);

            sBtnNextPic = oJQBtnNext.attr("src");
            sBtnNextPicDisable = getDiablePicName(sBtnNextPic);

            updateBtnState();

            oJQBtnPrev.bind("click", this.onPrev);
            oJQBtnNext.bind("click", this.onNext);
        }
    };
};

//********************************
// search functions
//********************************
var CPSearch = new function() {
    var iSaveCount = 9;
    var aryKeywords = new Array(iSaveCount);
    var iCurrentIdx = 0;
    var sCookieName = "searchkw";
    var sCookieIntv = "||";

    var getKeywords = function() {
        var aryRtn = new Array();
        var iPt = iCurrentIdx;
        do {
            if (aryKeywords[iPt] != undefined) aryRtn.push(aryKeywords[iPt]);
            iPt = iPt == aryKeywords.length ? 0 : iPt + 1;
        } while (iPt != iCurrentIdx);
        return aryRtn;
    };

    this.validateParam = function(sKW) {
        var sRtn = "";
        if (typeof (sKW) != "string") return sRtn;

        var aryValue = "0123456789abcdefjhijklmnopqrstuvwxyzABCDEFJHIJKLMNOPQRSTUVWXYZ_- \"®™±";
        for (var i = 0; i < sKW.length; i++) {
            var sChar = sKW.charAt(i);
            if (aryValue.indexOf(sChar, 0) >= 0) sRtn += sChar;
        }

        return sRtn;
    };

    this.addKeyword = function(sKW) {
        if (!sKW) return;

        aryKeywords[iCurrentIdx] = sKW;
        iCurrentIdx = iCurrentIdx == aryKeywords.length ? 0 : iCurrentIdx + 1;

        this.updateList();
        this.save();
    };

    this.updateList = function() {
        if ($("#functionarea").length == 0) return;
        var sHtmlList = "";
        var aryResult = getKeywords();
        if (aryResult.length == 0) {
            $("dd.records > p").show();
            $("dd.records > ul").html(sHtmlList);
        } else {
            for (var i = 0; i < aryResult.length; i++) {
                sHtmlList += "<li><a href='#' onclick='return newSearch(this)'>" + aryResult[i] + "</a></li>\n";
            }
            $("dd.records > p").hide();
            $("dd.records > ul").html(sHtmlList);
        }
    };

    this.save = function() {
        var sCookie = "";
        var aryKW = getKeywords();
        for (var i = 0; i < aryKW.length; i++) {
            if (aryKW[i].length) sCookie += (sCookie.length ? sCookieIntv : "") + aryKW[i];
        }
        setCookie(sCookieName, sCookie);
    };

    this.load = function() {
        var sCookie = getCookie(sCookieName);
        if (sCookie && sCookie.length) {
            var aryTmp = sCookie.split(sCookieIntv);
            for (var i = 0; i < aryTmp.length; i++) aryKeywords[i] = aryTmp[i];

            iCurrentIdx = aryTmp.length;
            if (iCurrentIdx == aryKeywords.length - 1) iCurrentIdx = 0;
        }
    };

    this.restore = function() {
        this.load();
        this.updateList();
    };
};

function searchSubmit() {
    var sInput = "kw";
    var sMsg = "input keywords here ...";
    var oJKW = $("#" + sInput);
    var sKWOld = oJKW.val();
    /*if (!sKWOld || sMsg==sKWOld) {
        oJKW.val(sMsg);
        return false;
    }*/
    
    if (CPSearch) {
        var sKW = CPSearch.validateParam(sKWOld);
        if (sKW != sKWOld) oJKW.val(sKW);
        CPSearch.addKeyword(sKW);
    }
    return true;
}

function newSearch(obj, needQuote) {
    var sKW = $(obj).text();
    if (needQuote) sKW = "\"" + sKW + "\"";
    $("#kw").val(sKW);

    if (CPSearch) CPSearch.addKeyword(sKW);
    $("#frmsearch").submit();
    
    return false;
}

/*
* page load event, deal with nav search function
*/
$(function() {
    CPSearch.restore();

    //enable "back" to category list page with browser "back"
    if ($("div#searchbox").length) {
        if ($.browser.mozilla) {
            $(window).bind("pageshow", function() { CPSearch.restore(); });
        } else {
            setTimeout(function() {
                CPSearch.restore();
            }, 0);
        }
    }
});

//*******************************
// nav header functions
//********************************
var CPHeader = new function() {
    var oShowBoxHandlers;
    var oShowBoxs;
    this.change_head_view = function(idx) {
        if (!this.oShowBoxs) this.oShowBoxs = $("div.showbox > div");
        if (!this.oShowBoxHandlers) this.oShowBoxHandlers = $("div#functionarea>div.btns>ul>li>a");

        this.oShowBoxs.each(function(i) {
            if (idx == i) $(this).show(); else $(this).hide();
        });

        this.oShowBoxHandlers.each(function(i) {
            if (idx == i) $(this).addClass("blackbg"); else $(this).removeClass("blackbg");
        });
    };
};

//*************************************
//* alternative comparison functions
//*************************************
var CPAlternative = new function() {
    var aryAlt = [null, null, null, null];

    var getModel = function(sId, sKey, sName, nPrice, sPic, bAdd) {
        return { id: sId, key: sKey, name: sName, price: nPrice, picture: sPic };
    };

    this.length = function() {
        var iRtn = 0;
        for (var i = 0; i < aryAlt.length; i++) {
            if (aryAlt[i] != null) iRtn++;
        }
        return iRtn;
    }

    var selected = function(sId) {
        for (var i = 0; i < aryAlt.length; i++) {
            if (aryAlt[i] && aryAlt[i].id==sId ) return true;
        }
        return false;
    };

    this.add = function(sId, sKey, sName, nPrice, sPic, bAdd) {
        var iRtn = -1;

        for (var i in aryAlt) {
            if (aryAlt[i] != null && aryAlt[i].id == sId) return i;
        };
        for (var i in aryAlt) {
            if (aryAlt[i] == null) {
                aryAlt[i] = getModel(sId, sKey, sName, nPrice, sPic);

                save();

                return i;
            };
        };
        return iRtn;
    };

    this.del = function(sId) {
        for (var i in aryAlt) {
            if (aryAlt[i] != null && aryAlt[i].id == sId) {
                aryAlt[i] = null;

                save();
                this.update_ui(true);

                return i;
            };
        };
        return -1;
    };

    var save = function() {
        var sSave = "";
        for (var i in aryAlt) {
            var sObject = "null";
            if (aryAlt[i] != null) {
                sObject = "{id:'" + aryAlt[i].id + "',key:'" + aryAlt[i].key + "',name:'" + aryAlt[i].name + "',price:" + aryAlt[i].price + ",picture:'" + aryAlt[i].picture + "'}";
            };
            sSave += (sSave.length > 0 ? "," : "") + sObject;
        };
        sSave = "[" + sSave + "]";
        setCookie("alternative", sSave);
    };

    var load = function() {
        var sLoad = getCookie("alternative");
        if (sLoad && sLoad.length > 0) aryAlt = eval(sLoad);
    };

    var update_list = function(bActive) {
        var sHtml = "";
        var sURL = "";

        if ($("div#comparebox").length == 0) return;

        //clear selection
        $("input[name='compare']").attr("checked", false);

        for (var i in aryAlt) {
            if (aryAlt[i] == null) {
                sHtml += '<dd ' + (i == aryAlt.length - 1 ? '' : 'class="space3px"') + '></dd>';
            } else {
                sHtml += '<dd ' + (i == aryAlt.length - 1 ? '>' : 'class="space3px">');
                sHtml += '<div><a href="/system/' + aryAlt[i].key + '/"><img src="' + aryAlt[i].picture + '" width="100"></a></div>';
                sHtml += '<h4>' + aryAlt[i].name + '</h4>';
                sHtml += '<ul>';
                sHtml += '<li><span class="cbprice">$' + aryAlt[i].price + '</span></li>';
                sHtml += '<li><a class="btn_details" href="/system/' + aryAlt[i].key + '/"><span>Details</span></a></li>';
                sHtml += '<li><a class="btn_customize" href="/system/' + aryAlt[i].key + '/detail"><span>Customize</span></a></li>';
                sHtml += '<li><a class="btn_remove" href="#" onclick="CPAlternative.del(\'' + aryAlt[i].id + '\'); return false;"><span>Remove</span></a></li>';
                sHtml += '</ul>';
                sHtml += '</dd>';

                sURL += (sURL.length ? ',' : '') + aryAlt[i].id;

                //set checked
                $("#chk_" + aryAlt[i].id).attr("checked", true);
            };
        };

        $("div#comparebox > dl").html(sHtml);
        $("#urlcompare").val(sURL);

        if (bActive) CPHeader.change_head_view(2);
    };

    /*update menu list in feature page*/
    var update_menu = function() {
        var sHtml = "";
        var sURL = "";
        var iCnt = 0;
        var oJQMenu = $("#featuremenu");

        if (oJQMenu.length == 0) return;

        for (var i in aryAlt) {
            if (aryAlt[i]) {
                iCnt++;
                sHtml += "<li><a class='left' href='/system/" + aryAlt[i].key + "/'>" + aryAlt[i].name + "</a><a class='right' href='#' onclick='CPAlternative.del(\"" + aryAlt[i].id + "\"); return false;'>clear</a></li>"
                sURL += (sURL.length ? ',' : '') + aryAlt[i].id;
            };
        };
        if (sHtml.length) sHtml += "<li><a class='cmpit' onclick='compareform.submit();return false;' href='#'>Compare these products</a></li>"

        //update input
        $("#urlcompare").val(sURL);

        //update menu
        oJQMenu.children("ul").html(sHtml);
        if (sHtml.length == 0) oJQMenu.hide();
        // --update check box selection
        var oJCheck = $("#chkcompare");
        if (oJCheck.length){
            oJCheck.attr("checked", selected(oJCheck.val()));
        }

        //update count
        $("#altercnt").html("(" + iCnt + ")");
    };

    /*update items in search page*/
    this.update_search = function() {
        var sCnt = this.length().toString();
        $(".tocompare > a > span").text("up to 4 items(" + sCnt + " selected) ");

        var sValue = "";
        for (var i in aryAlt) {
            if (aryAlt[i]) {
                sValue += (sValue.length ? "," : "") + aryAlt[i].id;
                $(":input[value='" + aryAlt[i].id + "']").attr("checked", "true");
            };
        };
        $("#urlcompare").val(sValue);
    };

    this.auto_show = function() {
        if (this.length() > 0) { CPHeader.change_head_view(2); }
    }

    this.add_del = function(sId, sKey, sName, nPrice, sPic, bAdd) {
        var nRtn = -1;

        if (bAdd && sId.substr(0, 4) == "NTBK") {
            alert("Sorry, but notebook can not be compared.");
        } else if (bAdd) {
            nRtn = this.add(sId, sKey, sName, nPrice, sPic);
            if (nRtn == -1) {
                alert("Sorry, but we can just handle up to 4 systems for the comparison.");
            }
        } else {
            nRtn = this.del(sId);
        }

        this.update_ui(true);

        return nRtn;
    };

    this.update_ui = function(bMemnuActive) {
        if ($("div#comparebox").length) {
            update_list(bMemnuActive);
        };
        if ($("#featuremenu").length) {
            update_menu();
        };
        if ($(".searchresults").length) {
            this.update_search();
        };
    };

    this.restore = function() {
        load();
        this.update_ui();
    };

    /* comparison list page - remove item */
    this.comp_list_del = function(idx, sId) {
        CPAlternative.del(sId);
        $("td[id*=" + idx + "]").html("");
    };

    /* comparison list page - expend all */
    this.comp_show_all = function() {
        $("tr[id*=pagelist]").toggle();
        $("h4[id*=lbl]").toggleClass("closeEx");
        $("#openall").toggleClass("caexpand");
    };

    /* comparison list page - expend a category */
    this.comp_show = function(sID) {
        $("tr[id*= " + sID + "]").toggle();
        $("#" + sID + "lbl").toggleClass("closeEx");
    };

};

/*
* page load even, deal with comparison function
*/
$(function() {
    //restore the varibles from session
    CPAlternative.restore();

    //enable "back" from the broswer for category list page
    // and deal with feature page menu
    if ($("div#comparebox").length || $("#featuremenu").length || $(".searchresults").length) {
        if ($.browser.mozilla) {
            $(window).bind("pageshow", function() { CPAlternative.restore(); /*CPAlternative.auto_show();*/ });
            $("input[name='compare']").attr("checked", false);
        } else {
            setTimeout(function() {
                $("ipnut[name='compare']").attr("checked", false);
                CPAlternative.restore();
                /*CPAlternative.auto_show();*/
            }, 0);
        }
    };
});


//********************************
// image loader function
//********************************
/*
* feature(list/compare) - change big picture 
*/
var ImageLoader = new function() {
    var sSrc = "";
    var oJQImg = null;
    var bIsLoading = false;
    var loader = new Image();

    var onLoad = function(e) {
        bIsLoading = false;
        if (oJQImg.attr("src") != sSrc) oJQImg.attr("src", sSrc);
    };

    var onFailed = function() {
        bIsLoading = false;
    };

    loader.onload = onLoad;
    loader.onerror = onFailed;
    loader.onerror = onFailed;

    this.loadImg = function(oJQImage, sImgSrc) {
        if (bIsLoading) return;
        bIsLoading = true;
        oJQImg = oJQImage;
        sSrc = sImgSrc;
        loader.src = sSrc;
    };
};

function chgGallery(sSrc, sID) {
    if (!sID) sID = "imgMain";
    ImageLoader.loadImg($("#" + sID), sSrc);
    return false;
}

//********************************
// image loader function
//********************************
/*
 * feature - change summary category item
 */
 /*
function changSummaryItem(sID) {
    var oCurrent = $("div.summary>div>div:visible");
    var oSelected = $("#" + sID);
    if (oSelected.attr("id") != oCurrent.attr("id")) {
        oCurrent.prev().children("span").toggleClass("wait").toggleClass("choose");
        oSelected.prev().children("span").toggleClass("wait").toggleClass("choose");
        oCurrent.hide();
        oSelected.show();
    }
}
*/

/*
* get spec
*/
function gs(p, n) {
    window.open("/spec/getspec.aspx?n=" + p + "&v=" + encodeURIComponent(n).replace(/\+/g, "%2b"), "spec", "width=640,height=480,location=no,menubar=no,status=no,toolbar=no,scrollbars=yes,resizable=yes").focus();
}

function SearchPost(){ 
    $("div .srbom a").bind("click", function(){
      alert( $(this).text() );
    }); 
}
