//********************************
// StringBuilder class
//********************************
function StringBuilder(val) {
    this.data = [];
    this.length = 0;

    this.append = function(val) { if (val) this.data.push(val); this.length += val.length; };
    this.clear = function() { this.data.length = this.length = 0; };
    this.toString = function() { return this.data.join(''); };
    if (typeof (val) != "undefined") this.append(val);
}

//********************************
// image loader function
//********************************
/*
* feature(list/compare) - change big picture 
*/
var ImageLoader = new function() {
    var sLodingImg = "/template/default/images/loading.gif";
    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);
            oJQImg.fadeIn("fast");
        }
    };

    var onFailed = function() {
        bIsLoading = false;
    };

    loader.onload = onLoad;
    loader.onerror = onFailed;
    loader.onabort = onFailed;

    this.loadImg = function(sImgId, sImgSrc) {
        if (bIsLoading) return;
        if ((!oJQImg && sImgId) || (sImgId && oJQImg && oJQImg.attr("id") != sImgId)) oJQImg = $("#" + sImgId);
        if (!oJQImg) return;
        if (sSrc != sImgSrc) {
            sSrc = sImgSrc;
            //oJQImg.hide();
            bIsLoading = true;
            loader.src = sSrc;
        }
    };
};

function chgGallery(sSrc, sID) {
    if (!sID) sID = "imgMain";
    ImageLoader.loadImg(sID, sSrc);
    return false;
}

function imgsw(id, src) {
    $("#" + id).attr("src", src);
    return false;
}


//********************************
// 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;
}




/*cpfavorite favorite popup */
var CPfavorite = new function() {
    var aryFav = [null, null, null, null,];
    this.exist=function(sId)
	{
        for (var i in aryFav) {
            if (aryFav[i] != null && aryFav[i] == sId) return true;
        };
		return false;
	}
    this.add = function(sId) {
        for (var i in aryFav) {
            if (aryFav[i] != null && aryFav[i] == sId) return -1;
        };
        for (var i in aryFav) {
            if (aryFav[i] == null) {
                aryFav[i] = sId;

                save(); this.update_list(true);

                return i;
            };
        };
        
        
        return -1;
       
    };

    this.del = function(sId) {
        for (var i in aryFav) {
            if (aryFav[i] != null && aryFav[i] == sId) {
                aryFav[i] = null;

                save(); 
                return i;
            };
        };
       
        return -1;
        
    };

    var save = function() {
        var sSave = "";
        for (var i in aryFav) {
            var sObject = "null";
            if (aryFav[i] != null) {
                sObject = "'" + aryFav[i] + "'";
            };
            sSave += (sSave.length > 0 ? "," : "") + sObject;
        };
        sSave = "[" + sSave + "]";
        setCookie("favorite", sSave);
    }; 
	

    var load = function() {
        var sLoad = getCookie("favorite");
        if (sLoad && sLoad.length > 0) aryFav = eval(sLoad);
    };

    this.update_list = function(bActive) {
        for (var i in aryFav) {
            if (aryFav[i] != null) {
                $("#chkpop_"+aryFav[i]).attr("checked",true);
               
            };
        };
    };
    

    this.add_del = function(sId, 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);
            if (nRtn == -1) {
                alert("Sorry, but we can just handle up to 4 systems for the comparison.");
            }
        }
		else {
            nRtn = this.del(sId);
        }
       
		this.update_list();

         return nRtn;
    };
    this.removeall= function() {
            for (var i in aryFav) {
            if (aryFav[i] != null) {
                aryFav[i] = null;
                save(); 
             };
        };
       
    };
    


    this.restore = function() {
        load();
       this.update_list();
    };
    
    this.count = function(){
    	load();
    	var iRtn = 0;
    	for (var i=0;i<aryFav.length;i++) iRtn+=aryFav[i]?1:0;
    	return iRtn;
    }
        
};

//*************************************
//* alternative comparison functions
//*************************************
var CPAlternative = new function() {
    var aryAlt = [null, null, null, null,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) {
       CPfavorite.add_del(sId,false)
       
        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() {
        var sHtml = "";
        var sURL = "";

       // if ($("div#topfavorite").length == 0) return;

        //clear selection
        $("input[name='compare']").attr("checked", false);
   
     
        for (var i in aryAlt) {
            if (aryAlt[i] == null) {
                sHtml += '';
               
								
            } else {
                sHtml += '<dd ' + (i == aryAlt.length - 1 ? '>' : 'class="space3px">');
                sHtml+='<span><input type="checkbox"  value=\''+ aryAlt[i].id +'\'  name="chkpop" id="chkpop_'+ aryAlt[i].id +'" ' + (CPfavorite.exist(aryAlt[i].id)?' checked':'');
                sHtml+=' onclick=" CPfavorite.add_del(\''+aryAlt[i].id +'\', this.checked)";'
                sHtml+='/></span>';
				sHtml += '<div class="tfpre"><img src="' + aryAlt[i].picture + '"   style="width: 45px; height: 45px;" /></div>';
                sHtml += '<div class="tfinfo">'
				sHtml += '<h3>' + aryAlt[i].name + '</h3>';
			    sHtml += '<h4>$' + aryAlt[i].price + '</h4>';
				sHtml += '<div>'
                sHtml += '<a class="gobtn" href="/system/'+ aryAlt[i].id +'/"><span>Customize</span></a><a class="delbtn" title="remove this" href="#" onclick="CPAlternative.add_del(\'' + aryAlt[i].id + '\',false); return false;"><span>Remove</span></a>'
                sHtml += ' </div>'
			    sHtml += ' </div>'			        
                sHtml += '</dd>';
                sURL += (sURL.length ? ',' : '') + aryAlt[i].id;
               
                //set checked
                $("#chk_" + aryAlt[i].id).attr("checked", true);
            };
        };
       
        if (sHtml == '') //if (aryAlt.toString()==",,,")
        {
          sHtml="<dd style='text-align:left'> No systems added to the favorite.<br>Add systems here to compare.<dd>";
        }
       
        $("div#topfavorite  dl").html(sHtml);
		$("#urlcompare").val(sURL);
     
       
    };
    

   
    /*update fav*/
    this.update_fav= function() {
    CPfavorite.update_list(true);

    };

    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 favorite.");
            }
        }
		else {
		    
		   
           nRtn = this.del(sId);
            
        }
        
        this.update_ui(true);
       // setTimeout(this.update_fav,5000);
        
       
       
        /*CPfavorite.*/update_list();//update favorite  status
        return nRtn;
    };

    this.update_ui = function() {
        if ($("div#topfavorite").length) {
           
            update_list(true);
            
        };
      
      
       
    };

    this.restore = function() {
        load();
        this.update_ui();
    };
    
    this.removeall= function() {
      for (var i in aryAlt) {
      if (aryAlt[i] != null){
       CPAlternative.del(aryAlt[i].id) 
                
      }              
      }	
      CPfavorite.removeall();			
       this.update_ui();
    };
    
        /* comparison list page - remove item */
    this.comp_list_del = function(idx, sId) {
        CPAlternative.del(sId);
        $("td[id*=" + idx + "]").html("");
    };
};

/*footer show|hide*/
function footerShowHide() {
    var oJQFooter = $("#footer_sitemap");
    var oJQImg = $("img#footer_status", oJQFooter);
    var iHeightHide = 25;
    var iHeightShow = 300;
    var iHeightNew = oJQFooter.height() == iHeightHide ? iHeightShow : iHeightHide;
    var sImgSrc = oJQImg.attr("src");
    sImgSrc = iHeightNew == iHeightHide ? sImgSrc.replace("Close", "Open") : sImgSrc.replace("Open", "Close");
    oJQFooter.height(iHeightNew);
    oJQImg.attr("src", sImgSrc);
}

/*scroll to top*/
function scrollTop() {
    $('html, body').animate({ scrollTop: 0 }, 500);
}



//*************************************
//* favorite menu object
//*************************************
var menuFavoriteHelper = new function() {
    var oJQLink = null;
    var oJQPopup = null;
    
    var oRunStatus = {bInPopup:false};
    
    var show_hide_pop = function(bShow){
        if (bShow) oJQPopup.show(); else oJQPopup.hide();
    };
    
    var event_link_in = function(e){
        show_hide_pop(true);
    };
    var event_link_out = function(e){
        if (!oRunStatus.bInPopup) show_hide_pop(false);
    };
    var event_pop_in = function(e){
        oRunStatus.bInPopup = true;
    };
    var event_pop_out = function(e){
        oRunStatus.bInPopup = false;
        show_hide_pop(false);
    };
    
    this.create = function(){
        oJQLink = $("#likelink");
        oJQPopup = $("#topfavorite");
        
        oJQLink.hoverIntent({ interval: 0, over: event_link_in, timeout: 200, out: event_link_out });
        oJQPopup.hoverIntent({ interval: 0, over: event_pop_in, timeout: 200, out: event_pop_out });
    };
};

//*************************************
//* topsearch menu object
//*************************************
var menuSearchHelper = new function() {
    var oJQLink = null;
    var oJQPopup = null;
    
    var oRunStatus = {bInPopup:false};
    
    var show_hide_pop = function(bShow){
        if (bShow) oJQPopup.show(); else oJQPopup.hide();
    };
    
    var event_link_in = function(e){
        show_hide_pop(true);
    };
    var event_link_out = function(e){
        if (!oRunStatus.bInPopup) show_hide_pop(false);
    };
    var event_pop_in = function(e){
        oRunStatus.bInPopup = true;
    };
    var event_pop_out = function(e){
        oRunStatus.bInPopup = false;
        show_hide_pop(false);
    };
    
    this.create = function(){
        oJQLink = $("#searchlink");
        oJQPopup = $("#topsearch");
        
        oJQLink.hoverIntent({ interval: 0, over: event_link_in, timeout: 200, out: event_link_out });
        oJQPopup.hoverIntent({ interval: 0, over: event_pop_in, timeout: 200, out: event_pop_out });
    };
};


//*************************************
//* share menu object
//*************************************
var menuShareHelper = new function() {
    var oJQLink = null;
    var oJQPopup = null;

    var oRunStatus = { bInPopup: false };

    var show_hide_pop = function(bShow) {
        if (bShow) oJQPopup.show(); else oJQPopup.hide();
    };

    var event_link_in = function(e) {
        show_hide_pop(true);
    };
    var event_link_out = function(e) {
        if (!oRunStatus.bInPopup) show_hide_pop(false);
    };
    var event_pop_in = function(e) {
        oRunStatus.bInPopup = true;
    };
    var event_pop_out = function(e) {
        oRunStatus.bInPopup = false;
        show_hide_pop(false);
    };

    this.create = function() {
        oJQLink = $("#sharelink");
        oJQPopup = $("#addtoshare");

        oJQLink.hoverIntent({ interval: 0, over: event_link_in, timeout: 200, out: event_link_out });
        oJQPopup.hoverIntent({ interval: 0, over: event_pop_in, timeout: 200, out: event_pop_out });
    };
};


/*
* page load even 
*/
/*deal with navigator fix for ie6*/
$(function() {
    var oJQNav = null;
    var oJQMenu = null;
    if ($.browser.msie && $.browser.version < "7") {
        oJQNav = $("#navigations"); oJQMenu = $("#popmenu");
        oJQNav.css("position", "absolute"); oJQMenu.css("position", "absolute");
        $(window).scroll(function() {
            oJQNav.css("top", $(window).scrollTop() + "px");
            oJQMenu.css("top", $(window).scrollTop() + 42 + "px");
        });


    }
});


/*deal with comparison function*/
$(function() {
    //restore the varibles from session
    CPAlternative.restore();
    CPfavorite.restore();
    menuFavoriteHelper.create();
    menuSearchHelper.create();
    menuShareHelper.create();
    //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);
        }
    };
});

  
function addkw()
{
   var kw = $("#kw").val();
  CPSearch.addKeyword(kw);

}

function popaddtoshare() {
    
    $("#sharelink").mouseenter(
    function() {
    $("#addtoshare").show();
    });

    $("#addtoshare").mouseleave(
    function() {
    $("#addtoshare").hide();
    });

    $("#favoritelink").mouseenter(
    function() {
        $("#addtoshare").hide();
    });

    $("#printlink").mouseenter(
    function() {
        $("#addtoshare").hide();
    });            

}

function compareformsubmit() {
    var count=CPfavorite.count()
    if (count>=2)
    {
       document.f1.action = "/search/syscompare.aspx";
       document.f1.submit();
       return false;
    
    }	
    

}

function makeWin2(url, p_Width, p_Height) {
    agent = navigator.userAgent;
    windowName = "Sitelet";
	
    params  = "";
    params += "toolbar=0,";
    params += "location=0,";
    params += "directories=0,";
    params += "status=0,";
    params += "menubar=0,";
    params += "scrollbars=1,";
    params += "resizable=1,";
    if (p_Width == "null") {
		params += "width=500,";
		params += "height=350";
    } else {
		params += "width=" + p_Width+ ",";
		params += "height=" + p_Height;
    }

    // close the window to vary the window size
	if (typeof(win) == "object" && !win.closed) win.close();
	   
    win = window.open(url, windowName , params);

    if (agent.indexOf("Mozilla/2") != -1 && agent.indexOf("Win") == -1) win = window.open(url, windowName , params);
	
    if (!win.opener) win.opener = window;
	
    // bring the window to the front
    win.focus();	
}
