/*Following javascript is for changing the default button when user click the enter key*/
function SetDefaultButton(event, target) 
{
    if (event.keyCode == 13 &&
        !(event.srcElement &&
            (event.srcElement.tagName.toLowerCase() =="textarea")))
    {
        try
        {
            event.cancelBubble = true;
            event.returnValue = false;
            event.cancel = true;
        }
        catch (err) {}
        
        if (event.stopPropagation)
            event.stopPropagation();
      
        if (event.preventDefault)
            event.preventDefault();
        
        $('#' + target).click();
        return false;
    }
}
function fnOnUpdateValidatorsMessages() {
    for (var i = 0; i < Page_Validators.length; i++) {
        var val = Page_Validators[i];
        var ctrl = document.getElementById(val.controltovalidate);
        if (ctrl != null && ctrl.style != null) {
            val.isvalid ? $(ctrl).removeClass("errorControl") : $(ctrl).addClass("errorControl");
        $(ctrl).blur(function() {
                       validateFields();
                     });
    }
}
}
function GetQOValue (queryValue, objectName)
{
    /*Get Query Object Value*/
    if ($('#' + objectName).length > 0)
    {
        return  queryValue + escape($('#' + objectName).val());
    }
}

function AddPartToCart(bpID, filePath, insertType, btn)
{
    var parentDiv = $(btn).parent();
    $('html, body').animate({scrollTop:0}, 'fast');
    $("[name='cartLink']:visible").data('tooltip').ajaxing = true;
    $("[name='cartLink']:visible").trigger('customShowEvent1');
    
    try{    $('a[rel="#quicklook_overlay"]').each(function(){$(this).data('overlay').close();}); }
    catch(err){}
    
    /*its relative so that the uk eu sit ewill work too.*/
    var url = filePath +'store/checkout/addtocart.aspx';
    var qParam ='FormType=insert';
    if ($('#' + bpID + '_mdl'))
    {
        qParam += '&model=' + escape($('#' + bpID + '_mdl').val());
    }
    if ($('#' + bpID + '_bpn'))
    {
        qParam += '&basepartno=' + escape($('#' + bpID + '_bpn').val());	
    }
    if ($('#' + bpID + '_pn'))
    {
        qParam += '&partno=' + escape($('#' + bpID + '_pn').val());	
    }
    if ($(parentDiv).children('#' + bpID + '_qty').length > 0)
    {
        qParam += '&qty=' + escape($(parentDiv).children('#' + bpID + '_qty').val());	
    }
    else if($('#' + bpID + '_qty').length > 0)
    {
        qParam += '&qty=' + escape($('#' + bpID + '_qty').val());
    }
    qParam += '&instype=' + escape(insertType);	
    
    $.ajax({ 
        url: url,
        async:false,
        data: qParam,
        success: function( data ) {
            /*If the result was notify send the customer to that page.*/
            if(data.indexOf('form name="aspnetForm" method="post" action="notify.aspx') >0) {
                window.location = url + '?' + qParam;
            }
            else {
            BaseCartUpdateAjax();
            }
         }
    });
    
    try {
            if (s_gi != null) {
                var s = s_gi(s_account);
                s.linkTrackVars = 'prop30,events,evar17';
                var site = GetSiteDir();
                var data = getCookie(site + 'CartQty');
                
                if(parseInt(data) > 1)
                {
                    s.events ='scadd';
                }
                else
                {
                    s.events ='scopen,scadd';
                }
                s.eVar17 =escape(insertType);
                s.tl("", 'o', btn);
            }
        }
        catch (e) {
        } 

    
}
function closeCart()
{
    $("[name='cartLink']:visible").data('tooltip').readytohide=true;
    $("[name='cartLink']:visible").trigger('customCloseEvent1');
}
function BaseCartUpdateAjax()
{
    var cartTimeout = setTimeout("closeCart();", 6000);
    $("[name='cartLink']:visible").data("tooltip").ajaxing = false;
    var wrap = $("[name='cartLink']:visible").data("tooltip").getTip().find(".contentWrap");
    var link = $("[name='cartLink']:visible").data("tooltip").cartlink;
    var theframe = $('<iframe frameborder="0" scrolling="auto" src="'+link+'" style="height:130px; width:220px; border:none;"></iframe>');
    wrap.html(theframe);
    HeaderCartUpdate();    
}

function HeaderCartUpdate()
{
    var site = GetSiteDir();
    var data = getCookie(site + 'CartQty');
    var sessionData = getCookie(site + 'NewSession');
    if(parseInt(data) > 0)
    {
        $('span[name="_CART_TOTAL"]').show();
        $('span[name="_CART_TOTAL"]').html(data);
    }
    else
    {
        try
        {
            if (parseInt(sessionData) >0) {
                $('span[name="_CART_TOTAL"]').hide();
            }
            else{ 
                setCookie (site + 'NewSession' ,'1','','/');
                /*make an ajax call for recording the search*/
                var link = $("[name='cartLink']:visible").data("tooltip").cartlink;
                $.ajax({
                    url: link, 
                    async:false,
                    dataType:'html',
                    success: function(data){
                        var beginIdx, endIndx;
                        beginIdx = data.indexOf('<strong class="emphasis">');
                        endIndx =  data.indexOf('</strong> item(s)');
                        if (beginIdx > 0 && endIndx > beginIdx ){
                            var cartQty = data.substr(beginIdx +25, (endIndx -beginIdx -25));
                            
                             setCookie (site + 'CartQty' ,cartQty,'','/');
                            $('span[name="_CART_TOTAL"]').show();
                            $('span[name="_CART_TOTAL"]').html(cartQty);
                        }
                        else {
                            $('span[name="_CART_TOTAL"]').hide();
                        }
                    }
                });
            }
        }
        catch (excp)
        {
            $('span[name="_CART_TOTAL"]').hide();
        }
        
    }
}

function ChangeDepartment(radioList, suffix)
{
    $("#" + radioList.id +" > option").each(function() {
        DivDisplay (suffix +this.value , "none");
        
    });
    var selected = $("#" + radioList.id + " option:selected");    
    if(selected.val() != 0){
        DivDisplay (suffix +selected.val() , "inline");
    }
}
function AddPartToRMACart(orderNo, filePath, insertType)
{
    /*its relative so that the uk eu sit ewill work too.*/
    var url = filePath +'support/rma/ordersearch.aspx?FormType=insert';
    url += '&orderno=' + escape(orderNo);	
	var linePos;
	var key;
    var totalLineItems;
    var qtyFound;
    if ($('#'+orderNo + '_total_qty').length > 0)
    {
        totalLineItems = $('#' + orderNo + '_total_qty').val();
        url += '&totalline=' + escape(totalLineItems);
        qtyFound = false;
        for (i = 0 ; i < totalLineItems ; i ++)
        {
            linePos = i +1; 
            key = 'BP_' + linePos + '_' + orderNo  + '_rma_qty';
            if ($('#'+key).length > 0 && $('#'+key).val() != '')
            {
                
                
                if ($('#'+key).val().indexOf(".") >=0 )
                {
                    alert('The returned Qty needs to be an Integer');
                    return false;
                }
                
                if (Number($('#'+key).val()) > 20)
                {
                    var option = confirm('To return more than 20 items, please call to continue RMA. Do you want to cancel RMA and move to support page?')
                    if(option)
		    {
	                    url = '/contact/index.aspx';
	                    window.location = url;
		    	return false;
                    }
                }
                
                
                qtyFound = true;
                /*first line has hte line Number an dqty*/
                url += GetQOValue ('&line' + linePos +'=rma_qty_' + linePos +';' ,key) ;
                /*the other values are ; dilimited.*/
                key = 'BP_' + linePos + '_' + orderNo  + '_mat_no';
                url +=  GetQOValue (';' ,key);
                key = 'BP_' + linePos + '_' + orderNo  + '_data_pn';
                url +=  GetQOValue (';' ,key);
                key = 'BP_' + linePos + '_' + orderNo  + '_data_orig_qty';
                url +=  GetQOValue (';' ,key);
                key = 'BP_' + linePos + '_' + orderNo  + '_data_line';
                url +=  GetQOValue (';' ,key);
            }
        }
    }
    if (qtyFound) 
    {
        window.location = url;
    }
    else
    {
        alert ('Please select a Qty to return');
        return false;
    }
}

function UpdateRMACart(filePath, key)
{

    /*its relative so that the uk eu sit ewill work too.*/
    var url = filePath +'support/rma/ordersearch.aspx?a=U';
    url += '&key=' + escape(key);	
    url += GetQOValue('&newQTY=','qty_'+key);
	
    window.location = url;
}
function NotifyPart(bpID, filePath)
{
    /*its relative so that the uk eu sit ewill work too.*/
    var url;
    url = filePath +'store/notify.aspx?FormType=notify';
    
    if ($('#' + bpID + '_mdl').length > 0)
    {
        url += '&model=' + escape($('#' + bpID + '_mdl').val());
    }
    if ($('#' + bpID + '_bpn').length > 0)
    {
        url += '&basepartno=' + escape($('#' + bpID + '_bpn').val());
    }
    if ($('#' + bpID + '_pn').length > 0)
    {
        url += '&partno=' + escape($('#' + bpID + '_pn').val());
    }
    if ($('#' + bpID + '_qty').length > 0)
    {
        url += '&qty=' + escape($('#' + bpID + '_qty').val());
    }
    window.location = url;
}
function AddToCart (available, bpID, filePath, insertType)
{
    var url;
    if (available == 'N')
    {
        url = filePath +'pvtcontent/notify.aspx?';
    }
    else
    {
        url = filePath +'store/checkout/addtocart.aspx?FormType=insert';
    }
    if ($('#' + bpID + '_mdl').length > 0)
    {
        url += '&model=' + escape($('#' + bpID + '_mdl').val());
    }
    if ($('#' + bpID + '_bpn').length > 0)
    {
        url += '&basepartno=' + escape($('#' + bpID + '_bpn').val());	
    }
    if ($('#' + bpID + '_pn').length > 0)
    {
        url += '&partno=' + escape($('#' + bpID + '_pn').val());
    }
    if ($('#' + bpID + '_qty').length > 0)
    {
        url += '&qty=' + escape($('#' + bpID + '_qty').val());
    }
    url += '&instype=' + escape(insertType);
    
    window.location = url;
    

}

function PromoValue ( filePath, actionType,promokey, bpKey)
{
    url = filePath +'store/checkout/addtocart.aspx?FormType=' +escape(actionType);
    
    if ($('#' + promokey + 'type'))
    {
        url += '&promotype=' + escape($('#' + promokey + 'type').val());	
    }
    if ($('#' + promokey + 'mdl'))
    {
        url += '&model=' + escape($('#' + promokey + 'mdl').val());	
    }
    if ($('#' + promokey +'qty'))
    {
        url += '&qty=' + escape($('#' + promokey +'qty').val());	
    }
    if ($('#' + promokey +'org_line'))
    {
        url += '&orgLineID=' + escape($('#' + promokey +'org_line').val());	
    }
    if ($('#upgBP_' + bpKey))
    {
        url += '&basepartno=' + escape($('#upgBP_' + bpKey).val());	
    }
    if ($('#upgEXT_' + bpKey))
    {
        url += '&partno=' + escape($('#upgEXT_' + bpKey).val());	
    }
    if ($('#upgECnt_' + bpKey))
    {
        url += '&ecount=' + escape($('#upgECnt_' + bpKey).val());	
    }
    url += '&instype=' + escape(actionType);	

    window.location = url;
}

function BuildMemorySelectorURL (path, param1Value, param2, param2Value)
{
    var url =path;
    url = path + escapeURL(param1Value) + param2 + escapeURL(param2Value);
    /*if cat exist in the query string then set it.*/
    if (url.indexOf("cat") < 0 )
    {
        if ($('#hidCAT').length > 0)
        {
            url = url + '&cat=' + escape($('#hidCAT').val())
        }
    }
    window.location = url;
}


function SearchClick(configView, refOid,refType,refName,searchGroup,path,param1Value)
{
    /*make an ajax call for recording the search*/
    $.ajax({
        url: '/ajax/_logChanges.aspx', 
        data: 'DSName=logsearchrank&cv=' + escape(configView) + '&ref_oid=' + escape(refOid) + '&ref_type=' + escape(refType)+ '&ref_name=' + escape(refName)+ '&search_group=' + escape(searchGroup),
        success: function(data){
            $('#dummytrackingdiv').html(data);
        }
    });
    /*then make hte Memory Selector URL.*/
    BuildMemorySelectorURL(path,param1Value,'','');
}
function DropDownChanged(path, ddlid, param2, param2Value)
{
    if ($('#'+ddlid).val() != 'none')
    {   
        BuildMemorySelectorURL(path,$('#'+ddlid).val(),param2,param2Value);
    }
    else
    {
        alert ("Please make a selection");
    }
}

function ValidatePaymentPage()
{
    var isValid = true;
    
    if (!IsFieldValid('card_holderName'))
    {
        isValid =false;
    }
    if (!IsFieldValid('card_cardType'))
    {
        isValid =false;
    }
    if (!IsFieldValid('card_accountNumber'))
    {
       isValid =false;
    }
    if (!IsFieldValid('card_cvNumber'))
    {
        isValid =false;
    }
    
    
    if (!IsFieldValid('card_expirationMonth') ||!IsFieldValid('card_expirationYear') )
    {
        isValid =false;
        DivDisplay ( "card_expirationDate_error","inline");
    }
    else
    {
        DivDisplay ( "card_expirationDate_error","none");
    }
  
    if (IsFieldValid('card_cardType') && IsFieldValid('card_accountNumber'))
    {
        if (!IsFieldCC('card_cardType','card_accountNumber'))
        {
            isValid =false;
        }
    }
    if (IsFieldValid('card_cardType') && IsFieldValid('card_cvNumber'))
    {
        if (!IsFieldCID('card_cardType','card_cvNumber'))
        {
            isValid =false;
        }
    }
    if (!isValid )
    {
        return false;
    }
    else
    {
        try {
            if($("#card_holderName").val().length > 0 && $("[name='billTo_firstName']").length > 0 && $("[name='billTo_lastName']").length > 0){
                var mySplitResult =$("#card_holderName").val().split(" ");
                var lastName ="";
                $("[name='billTo_firstName']")[0].val(mySplitResult[0]);
                for(i = 1; i < mySplitResult.length; i++){
                    lastName = lastName + mySplitResult[i] +" "; 
                }
                if (lastName.length >0){
                    $("[name='billTo_lastName']")[0].val(lastName);
                }
            }
        }
        catch (excp){ }
        return true;
    }
}
function DivDisplay(szDivID, displayID) // 1 visible, 0 hidden
{
	var theSpan = document.getElementById ? document.getElementById(szDivID) : document.all ? document.all[szDivID] : (new Object());
	if( !theSpan ) { return; } if( theSpan.style ) { theSpan = theSpan.style; }
	{
		theSpan.display = displayID;
	}
}
// This returns a string with everything but the digits removed.
function getdigits (s) {
   return s.replace (/[^\d]/g, "");
}
function IsFieldCID(typeName, fieldName)
{
    try
    {
        var ccType = $('#'+typeName).val();
        var cID = getdigits($('#'+fieldName).val());
        {
            var lengthCheck =0;
            switch (ccType) 
            {
                case '001': lengthCheck =3 ;break;
                case '002': lengthCheck =3;break;
                case '003': lengthCheck =4;break;
                case '004': lengthCheck =3;break;
            }
            if (lengthCheck >0 && cID.length <lengthCheck)
	        {
                DivDisplay ( fieldName +"_error","inline");
                return false;
            }
            else
            {
                DivDisplay ( fieldName +"_error","none");
            }
        }
    }
    catch (excp){ }
    return true;
}

function IsFieldCC(typeName, fieldName)
{
    try
    {
        var ccType = $('#'+typeName).val();
        var ccNum = getdigits($('#'+fieldName).val());
        {
            var goodCC ="/^[0-9]{15,16}$/";
            switch (ccType) 
            {
                case '001': goodCC="^4[0-9]{15}$";break;
                case '002': goodCC="^5[1-5]{1}[0-9]{14}$";break;
                case '003': goodCC="^3[47]{1}[0-9]{13}$";break;
                case '004': goodCC="^6011[0-9]{12}$";break;
            }
            var reg = new RegExp(goodCC);
	        if(!reg.test(ccNum))
            {
                DivDisplay ( fieldName +"_error","inline");
                return false;
            }
            else
            {
                DivDisplay ( fieldName +"_error","none");
            }
        }
    }
    catch (excp){ }
    return true;
}

function IsFieldValid(fieldName)
{
    if ($('#'+fieldName).length > 0)
    {
        if ($('#'+fieldName).val().length ==0)
        {
            DivDisplay ( fieldName +"_error","inline");
             return false;
        }
        else
        {
            DivDisplay ( fieldName +"_error","none");
        }
    }
    return true;
}


function ChangeImage(imageId, imagePath)
{
    if ($("#" + imageId).length > 0)
    {
        $("#" + imageId).attr("src",imagePath);
    }
}

function SmallPopup(page) {
    OpenWin = this.open(page, "CtrlWindow", "toolbar=no,menubar=no,directories=no,location=no,scrollbars=yes,resize=yes,height=550,width=550,left=20,top=20");
}

function openWin(url, windowName, width, height, scrollbars) {
    var win;
    var params;
    var windowName;
    params = "toolbar=0,";
    params += "location=0,";
    params += "directories=0,";
    params += "status=0,";
    params += "menubar=0,";
    params += "scrollbars="+scrollbars+",";
    params += "resizable=1,";
    params += "top=20,";
    params += "left=20,";
    params += "width="+width+",";
    params += "height="+height;

    win = window.open(url, windowName, params);
}

/*used by Search */
function SubmitSearch (filePath, searchTextBox, orgSearchKeyword)
{
    var url;
    /*this function is called from master pages, search results pages.
    from master page is the search test bos is empty then it goes to search index page*/
    if ($('#' + searchTextBox).length > 0 && $('#' + searchTextBox).val() != '')
    {
        url =filePath + 'search/searchresults.aspx?keywords=' ;
        if (orgSearchKeyword != '')
        {
            url += escape(orgSearchKeyword) + ' ';
        }
        url +=  escape($('#' + searchTextBox).val());
    }
    else
    {
        url =filePath + 'search/index.aspx' ;
    }
    $('form').attr('action', url);
    window.location.href = url;    
    return false;
} 

function SubmitSearchAll (filePath, searchTextBox, orgSearchKeyword,searchGroup)
{
    var url;
    /*this function is called from master pages, search results pages.
    from master page is the search test bos is empty then it goes to search index page*/
    if ($('#'+searchTextBox).length > 0 && $('#'+searchTextBox).val() != '')
    {
        url =filePath + 'search/searchall.aspx?rowcount=20&keywords=' ;
        if (orgSearchKeyword != '')
        {
            url += escape(orgSearchKeyword) + ' ';
        }
        
        url +=  escape($('#'+searchTextBox).val());
        if (searchGroup != '')
        {
            url += '&srchgroup=' + escape(searchGroup) ;
        }
    }
    else
    {
        url =filePath + 'search/index.aspx' ;
    }
    
    window.location = url;
}

function toggleBox(szDivID)
{
	var theSpan = document.getElementById ? document.getElementById(szDivID) : document.all ? document.all[szDivID] : (new Object());
	if( !theSpan ) { return; } if( theSpan.style ) { theSpan = theSpan.style; }
	{
		theSpan.display = ( theSpan.display == 'none' ) ? 'inline' :  'none';
	}
}

var newwindow;
function content(url)
{
	newwindow=window.open(url,'name','height=500,width=400,left=100,top=100,resizable=yes,scrollbars=yes');
	if (window.focus) {newwindow.focus()}
}

/*This function runs the regular escape() function and escapes "+" signs on the parameter string
and returns the resulting string - Evan Johnson 6-8-07*/
function escapeURL(theString)
{
    theString = escape(theString);
    if (theString.indexOf('+') != -1)
      return theString.replace(/\+/g,"%2B");
    else
      return theString;
}

/*changes the shipmethods via ajax.*/
function ChangeShipMethods(ddlCountry, ddlState, cartID)
{
    /*all the drop downs should exist.*/
    if ($('#'+ddlCountry).length > 0 && $('#'+ddlState).length > 0)
    {
        $.ajax({
            url: '/ajax/_GetDropDownData.aspx',
            data: 'DSName=shipmethod&cf=ship_method_oid&df=ship_method_desc_amt&CountryCode=' + escape($('#'+ddlCountry).val()) + '&RegionCode=' + escape($('#'+ddlState).val()) + '&cartID=' + escape(cartID),
            success: _loadChangeShipMethods
        });
    }
}

function IsCheckBoxChecked(checkBox)
{
    if ($('#'+checkBox).val() == 'agree')
    {
        return true;
    }
    else
    {
        alert('Please select the check box');
        return false;
    }
}

function _loadChangeShipMethods(req) 
{
  var options = eval(req.responseText);
  if ($('#hidShipMethodClientID').length > 0){
    var d = $('#'+$('#hidShipMethodClientID').val());
    d.html('');

    if (options && options.length && options.length > 0){			
      for (var i = 0; i < options.length; i++) {
        $("<option value='"+options[i].value+"'>"+options[i].name+"</option>").appendTo(d);
      }
      d.get(0).selectIndex = 0;
    }
  }
}

function getRadioValue(idOrName) {
        var value = null;
        var element = document.getElementById(idOrName);
        var radioGroupName = null;  
        
        /* if null, then the id must be the radio group name*/
        if (element == null) {
                radioGroupName = idOrName;
        } else {
                radioGroupName = element.name;     
        }
        if (radioGroupName == null) {
                return null;
        }
        var radios = document.getElementsByTagName('input');
        for (var i=0; i<radios.length; i++) {
                var input = radios[ i ];    
                if (input.type == 'radio' && input.name == radioGroupName && input.checked) {                          
                        value = input.value;
                        break;
                }
        }
        return value;
}

function ShipMethodDropDownChange(radioShipMethodList)
{
    /*alert(getRadioValue(radioShipMethodList));*/
    try
    {
        DivDisplay("shipmethod_freeshipping","none");
        DivDisplay("shipmethod_RMSD_nextday","none");
        DivDisplay("shipmethod_RMSD","none");
        
        var radioBtnCollection = $.makeArray($("#" +radioShipMethodList.id + " input:radio"));
        $.each(radioBtnCollection,function(index,element){
            var  msgText = $("#" + element.id + " +label").text();
            var methodType;
            if (msgText.indexOf("Free Shipping") != -1) {
                methodType = 'freeshipping';
            }else if (msgText.indexOf("Next Bus") != -1) {
                methodType = 'RMSD_nextday';
            }else if (msgText.indexOf("Royal Mail Special Delivery") != -1) {
                methodType = 'RMSD';
            }
            if (element.checked)
                DivDisplay("shipmethod_" +methodType,"inline");

        });
    }
    catch (e) {
	}
    
}

function ShowRadioShipBusinessDay(radioShipMethodList, iCount, orderDate, resultDataID, site,freeDivID, freeshipid)
{
    /*alert(getRadioValue(radioShipMethodList));*/
    var selectedvalue = $("#" + radioShipMethodList + " input:radio:checked").val();
    if (selectedvalue == freeshipid) {
        DivDisplay (freeDivID,'block');
    }
    else {
        DivDisplay (freeDivID,'none');
    }
    $.ajax({
                url: '/ajax/_ShipBusinessDay.aspx', 
                data: 'site=' + escapeURL(site) + '&shipMethod=' + escape(selectedvalue) +  '&orderDate=' + escapeURL(orderDate),
                success: function(data){$('#'+resultDataID).html(data);}
            });
    
}

function ChangeTaxData(radioList)
{
    var radioBtnCollection = $.makeArray($("#" +radioList.id + " input:radio"));
    $.each(radioBtnCollection,function(index,element){
        if (element.checked)
            DivDisplay("rblTaxExemptReason_" +index.toString(),"inline");
        else
            DivDisplay("rblTaxExemptReason_"+index.toString(),"none");
     });


}
function ShowShipBusinessDay(ddlShipMethod, orderDate, resultDataID, site)
{
    $.ajax({
        url: '/ajax/_ShipBusinessDay.aspx',
        data: 'site=' + escapeURL(site) + '&shipMethod=' + escape($('#'+ddlShipMethod).val()) +  '&orderDate=' + escapeURL(orderDate),
        success: function(data){
            $('#'+resultDataID).html(data);
        }
    });
}   
   
function setTnT(cookieID, vsName)
{
    $.ajax({
        url: '/ajax/_tntVS.aspx',
        data: 'id=' + escapeURL(getCookie(cookieID)) + '&vs=' + escape(vsName)
    });
} 

/*v1.7
 Flash Player Version Detection
 Detect Client Browser type
 Copyright 2005-2007 Adobe Systems Incorporated.  All rights reserved.*/
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion()
{
	var version;
	var axo;
	var e;

	/* NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry */

	try {
		/* version will be set for 7.X or greater players */
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			/* version will be set for 6.X players only*/
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			
			/* installed player is some revision of 6.0
			 GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			 so we have to be careful. 
			
			 default to the first public version */
			version = "WIN 6,0,21,0";

			/* throws if AllowScripAccess does not exist (introduced in 6.0r47) */
			axo.AllowScriptAccess = "always";

			/* safe to call for 6.0r47 or greater */
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			/* version will be set for 4.X or 5.X player */
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			/* version will be set for 3.X player */
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			/* version will be set for 2.X player */
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}
	
	return version;
}

/* JavaScript helper required to detect Flash Player PlugIn version information */
function GetSwfVer(){
	/* NS/Opera version >= 3 check for Flash plugin in plugin array */
	var flashVer = -1;
	
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");			
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	/* MSN/WebTV 2.6 supports Flash 4*/
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	/* WebTV 2.5 supports Flash 3*/
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	/* older WebTV supports Flash 2*/
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}	
	return flashVer;
}

/* When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available*/
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			/* Given "WIN 2,0,0,11" */
			tempArray         = versionStr.split(" "); 	/* ["WIN", "2,0,0,11"] */
			tempString        = tempArray[1];			/* "2,0,0,11" */
			versionArray      = tempString.split(",");	/* ['2', '0', '0', '11']*/
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];

        	/* is the major.revision >= requested major.revision AND the minor version >= requested minor */
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
  var str = '';
  if (isIE && isWin && !isOpera)
  {
    str += '<object ';
    for (var i in objAttrs)
    {
      str += i + '="' + objAttrs[i] + '" ';
    }
    str += '>';
    for (var i in params)
    {
      str += '<param name="' + i + '" value="' + params[i] + '" /> ';
    }
    str += '</object>';
  }
  else
  {
    str += '<embed ';
    for (var i in embedAttrs)
    {
      str += i + '="' + embedAttrs[i] + '" ';
    }
    str += '> </embed>';
  }

  document.write(str);
}

function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
      case "id":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}
/*******DYNAMIC JS/CSS LOADING******/
var filesadded=""; /*list of files already added */

function checkloadjscssfile(filename, filetype){
 if (filesadded.indexOf("["+filename+"]")==-1){
  loadjscssfile(filename, filetype);
  filesadded+="["+filename+"]"; /*List of files added in the form "[filename1],[filename2],etc"*/
 }
}
function loadjscssfile(filename, filetype){
 if (filetype=="js"){ /*if filename is a external JavaScript file
  var fileref=document.createElement('script');
  fileref.setAttribute("type","text/javascript");
  fileref.setAttribute("src", filename);*/
  $.getScript(filename);
 }
 else if (filetype=="css"){ /*if filename is an external CSS file*/
  var fileref=document.createElement("link");
  fileref.setAttribute("rel", "stylesheet");
  fileref.setAttribute("type", "text/css");
  fileref.setAttribute("href", filename);
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref);
}

/************** generate a unique id ************/
var uid_counter = 0;
function getID() {
  var id = 'uid_' + uid_counter++;
  while(document.getElementById(id)) id = 'uid_' + uid_counter++;
  return id;
}

/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
function setCookie(name, value, expires, path, domain, secure)
{
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
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 unescape(dc.substring(begin + prefix.length, end));
}

/**
 * Deletes the specified cookie.
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */
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 displayLoggedUserName(loginNameCookie)
{
    try
    {
        var loggedUserName = getCookie(loginNameCookie);
        var objToShow;
        var username = $('#loggedUserName');
        if(loggedUserName != null)
        {
            objToShow = $('#loggedLink');
        }
        else
        {
            objToShow = $('#loginLink');
            if($('#loggedInContent').length > 0)
            {
                $('#loggedInContent').css('display','none');
            }
            loggedUserName = '';
        }        
        if (objToShow.length > 0)
        {
            objToShow.css('display', 'inline');
        }
        if (username.length > 0)
        {
            var cur = username.html();
            username.html(cur.replace("~*~LOGGED_IN_NAME~*~", loggedUserName));
        }		
    }
    catch (ex)
    {
        return true;
    }	
}

/*Code for Checking on Visit based on Country etc.
and show a Popup
*/
function checkAutoVisit(cookieName,cookieValue, popupURL, displayMessage, shopLabel) {

  /* Check last viewed version*/
  var cookie = getCookie(cookieName);
    
  if (cookie == null || parseFloat(cookie) < cookieValue) 
  {
     date=new Date;
    date.setMonth(date.getMonth()+3);
    setCookie(cookieName, cookieValue, date);
    
    showAutoPopupModal(popupURL, displayMessage, shopLabel);
  }
}

function showAutoPopupModal(popupURL, displayMessage, shopLabel) {

  Dialog.confirm(displayMessage, 
                   {top: 10, width:500, className: "alphacube", okLabel: shopLabel, cancelLabel:"No Thanks",onOk:function(win){
				   window.location = popupURL}})
}

/*********************************************************************
One Step Memory Selector
******************************************************/
(function($){
    var OneStepMemorySelector = function(element, options)
    {
        var elem = $(element);
        var obj = this;
        var defaults = {
            ddl1: null,
            cmdButton: null,
            stepName: 'RAMStep',
            basePartNo: '',
            memorySelector: true,
            configView: 'Crucial',
            serverName :'/',
            ddl1Name: 'Select Manufacturer',
            cat: 'RAM',
            filePath: '/'
        }
        var config = $.extend(defaults, options || {});
        var _ajaxRunning = false;
        var _url = '';
        var _ddl1 = config.ddl1;
        var _cmdButton =config.cmdButton;
        /*Init adds all teh events*/
        emptyDDL( _ddl1,config.ddl1Name);
        _ddl1.mouseover(loadDDL1);
        _ddl1.mouseleave(function(e){e.stopPropagation();});
        /*If the cmd button is defined then click on that for next*/
        if (_cmdButton) {
            _cmdButton.click(loadDDL1Finish);
        }else {
        _ddl1.change(loadDDL1Finish);
        }
        elem.click (cmdButtonClick);
        
        /*Public Methods*/
        this.SetCAT = function (cat) {
            config.cat = cat;
        }
        this.SetStepName = function (stepName) {
            config.stepName = stepName;
        }
        this.SetConfigView = function (configView) {
            config.configView = configView;
        }
        this.Setddl1Name = function (ddl1Name) {
            config.ddl1Name = ddl1Name;
        }
        this.Getddl1Name = function () {
            return config.ddl1Name;
        }
        this.SetBasePartNo = function (basePartNo) {
            config.basePartNo = basePartNo;
        }
        this.GetBasePartNo = function () {
            return config.basePartNo;
        }
        this.SetMemorySelector = function (memorySelector) {
            config.memorySelector = memorySelector;
        }
        this.IsMemorySelector = function () {
            return config.memorySelector;
        }
        
        /*Private Methods*/
        function emptyDDL(obj, defaulValue)
	{
            var options = '<option value="">' + defaulValue + '</option>';
            obj.html(options);
	}
        function loadDDL1(e, obj)
        {
            e.stopPropagation();
            if (_ddl1.length <=2 && _ajaxRunning == false)
            {
                _ajaxRunning= true;
		var url ='/ajax/_GetDropDownData.aspx';
		url += '?DSName=mfgrbycat&cf=mfgr_code&df=mfgr_code&cat=' + config.cat + '&cv=' + encodeURIComponent(config.configView);	
		$.ajax({url:url,dataType: 'html', 
                    beforeSend: function(x) {
                        if(x && x.overrideMimeType) {
                            x.overrideMimeType("application/j-son;charset=UTF-8");}},
                    success: function(data){
                        var eoptions = eval(data);
                        var options = '<option value="">' + config.ddl1Name + '</option>';
                        if (eoptions && eoptions.length && eoptions.length > 0){
                            if (eoptions.length == 1 && eoptions[0].name =='N.A' ){
                                options += '<option value="(OTHERS)">All Models</option>'; 
                            }
                            else
                            {
                                for (var i = 0; i < eoptions.length; i++) {
                                    options += '<option value="' + eoptions[i].value + '">' + eoptions[i].name + '</option>';   
                                }
                            }
                        }
                        _ddl1.html(options);
                    }
                });
            }
        }
	
	function loadDDL1Finish(event)
        {
            var mfgrValue =_ddl1.val();
            if (mfgrValue!= 'Select'){
                _url = config.filePath + 'store/listproductline.aspx?mfgr=' + encodeURIComponent(mfgrValue);        
            }
        }
	
	function cmdButtonClick(event)
        {
            if (_url !='')
            {
                window.location = _url ;
            }
        }
    }
    $.fn.onestepmemoryselector = function(options)
    {
        return this.each(function()
        {
            var element = $(this);
            if(element.data('onestepmemoryselector')) return;
            var onestepmemoryselector = new OneStepMemorySelector(this, options);
            $(this).data('onestepmemoryselector', onestepmemoryselector);
        });
    };
})(jQuery);

/*********************************************************************
Three Step Memory Selector
******************************************************/
(function($){
    var ThreeStepMemorySelector = function(element, options)
    {
        var elem = $(element);
        var obj = this;
        var defaults = {
            ddl1: null,
            ddl2: null,
            ddl3: null,
            cmdButton: null,
            stepName: 'RAMStep',
            basePartNo: '',
            memorySelector: true,
            filePath: '/',
            serverName :'/',
            configView: 'Crucial',
            ddl1Name: 'Select Manufacturer',
            ddl2Name: 'Select Product Line',
            ddl3Name: 'Select Model',
            cat: 'RAM'
        }
        var config = $.extend(defaults, options || {});
        var _ajaxRunning = false;
        var _url = '';
        var _ddl1 = config.ddl1;
        var _ddl2 = config.ddl2;
        var _ddl3 = config.ddl3;
        
        emptyDDL( _ddl1, config.ddl1Name); 
	emptyDDL( _ddl2, config.ddl2Name); 
	emptyDDL( _ddl3, config.ddl3Name);
        _ddl1.mouseover(loadDDL1);
        _ddl1.change (loadDDL2);
        _ddl2.change (loadDDL3);
        _ddl3.change (loadDDL3Finish);
        elem.click (cmdButtonClick);
        elem.addClass('selectorbtnDisabled');
        
        this.SetCAT = function (cat) {
            config.cat = cat;
        }
        this.SetStepName = function (stepName) {
            config.stepName = stepName;
        }
        this.SetConfigView = function (configView) {
            config.configView = configView;
        }
        this.SetFilePath = function(filePath) {
            config.filePath = filePath;
        }
        this.Setddl1Name = function (ddl1Name) {
            config.ddl1Name = ddl1Name;
        }
        this.Getddl1Name = function () {
            return config.ddl1Name;
        }
        this.Setddl2Name = function (ddl2Name) {
            config.ddl2Name = ddl2Name;
        }
        this.Getddl2Name = function () {
            return config.ddl2Name;
        }
        this.Setddl3Name = function (ddl3Name) {
            config.ddl3Name = ddl3Name;
        }
        this.Getddl3Name = function () {
            return config.ddl3Name;
        }
        this.SetBasePartNo = function (basePartNo) {
            config.basePartNo = basePartNo;
        }
        this.GetBasePartNo = function () {
            return config.basePartNo;
        }    	
        this.SetMemorySelector = function (memorySelector) {
            config.memorySelector = memorySelector;
        }
        this.IsMemorySelector = function () {
            return config.memorySelector;
        }
        function emptyDDL(obj, defaulValue)
        {
            var options = '<option value="">' + defaulValue + '</option>';
            obj.html(options);
        }
        function SetActiveStep(nameExtn, stepId, totalCount)
        {
            var nameExtnId;
            for (i=1; i<= totalCount; i++)
    	    {
	        nameExtnId ='#' + nameExtn+ i;			
	        if ($(nameExtnId).length > 0){
                    if (i == stepId){
                        $(nameExtnId).removeClass('label');
		        $(nameExtnId).addClass ( 'labelactive');
	            }
	            else{
		        $(nameExtnId).removeClass( 'labelactive');
		        $(nameExtnId).addClass( 'label');
		    }
                }            
    	    }
    	    if(stepId > totalCount){
                elem.addClass('selectorbtn');
                elem.removeClass('selectorbtnDisabled');
            }
            else{
                elem.addClass('selectorbtnDisabled');
                elem.removeClass('selectorbtn');
            }
        }
        function ajaxLoadDDL(url, ddl, ddlName)
        {
            $.ajax({
                url:url, dataType: 'html',
                beforeSend: function(x) {
                    if(x && x.overrideMimeType) {
                        x.overrideMimeType("application/j-son;charset=UTF-8");
                    }
                },
                success: function(data){
                    var eoptions = eval(data);
                    var options = '<option value="">' + ddlName + '</option>';
                    if (eoptions && eoptions.length && eoptions.length > 0) {
                        if (eoptions.length == 1 && eoptions[0].name =='N.A' ){
                            options += '<option value="(OTHERS)">All Models</option>'; 
                        }
                        else {
                            for (var i = 0; i < eoptions.length; i++) {
                                options += '<option value="' + eoptions[i].value + '">' + eoptions[i].name + '</option>';   
                            }
                        }
                    }
                    ddl.html(options);
                }
           });
        }
        function loadDDL1(e, obj)
        {
            if (_ddl1.length <=2 && _ajaxRunning == false){
                _ajaxRunning= true;
                SetActiveStep(config.stepName, 1,3);
                emptyDDL( _ddl2,config.ddl2Name);
                emptyDDL( _ddl3,config.ddl3Name);
	        var url ='/ajax/_GetDropDownData.aspx';
	        url += '?DSName=mfgrbycat&cf=mfgr_code&df=mfgr_code&cat=' + config.cat + '&cv=' + encodeURIComponent(config.configView);	
	        ajaxLoadDDL(url, _ddl1, config.ddl1Name);	    
	        loadDDL2(e, _ddl2);
            }
        }
    	
        function loadDDL2(e, obj)
        {
            emptyDDL( _ddl3,config.ddl3Name); 
	    var mfgrValue =_ddl1.val();	
	    if (mfgrValue!= 'Select' && mfgrValue != 'Select Manufacturer' && escape(mfgrValue) != 'null' && mfgrValue != 'N.A' && mfgrValue!= '' && mfgrValue != config.ddl1Name){
                SetActiveStep(config.stepName, 2,3);
                emptyDDL( _ddl2,'Loading...');
	        var url ='/ajax/_GetDropDownData.aspx';
	        url += '?DSName=plbymfgr&cf=product_line_code&df=product_line_code&cat=' + config.cat + '&mfgr=' + encodeURIComponent(mfgrValue) + '&cv=' + encodeURIComponent(config.configView);
	        ajaxLoadDDL(url, _ddl2, config.ddl2Name);
	        loadDDL3(e, _ddl3);
            }
        }
    	
        function loadDDL3(e, obj)
        {
            var mfgrValue =_ddl1.val();
            var plValue =_ddl2.val();
            if (mfgrValue!= 'Select' && mfgrValue != 'Select Manufacturer' && escape(mfgrValue) != 'null' && mfgrValue != 'N.A' && mfgrValue!= '' && mfgrValue != config.ddl1Name && plValue != 'Select' && plValue != 'Select Product Line' && escape(plValue) != 'null' && plValue != 'N.A' && plValue != config.ddl2Name && plValue !='')
            {
                SetActiveStep(config.stepName, 3,3);
                emptyDDL( _ddl3,'Loading...');
                var url ='/ajax/_GetDropDownData.aspx';
                url +='?DSName=modelbypl&cf=model_code&df=model_code&mfgr=' + encodeURIComponent(mfgrValue) + '&pl=' + encodeURIComponent(plValue) +'&cv=' + encodeURIComponent(config.configView);
                ajaxLoadDDL(url, _ddl3, config.ddl3Name);
            }
        }
        
        function loadDDL3Finish(event)
        {
            SetActiveStep(config.stepName, 4,3);
            var mfgrValue =_ddl1.val();
            var plValue =_ddl2.val();
            var modelValue =_ddl3.val();
    	
	    if (mfgrValue!= 'Select' &&  escape(mfgrValue) != 'null' && mfgrValue != 'N.A' && mfgrValue!= '' && mfgrValue != config.ddl1Name && plValue != 'Select' &&  escape(plValue) != 'null' && plValue != 'N.A' && plValue != config.ddl2Name && plValue !='' && modelValue != 'Select' &&  escape(modelValue) != 'null' && modelValue != 'N.A' && modelValue != config.ddl2Name && modelValue !='')
            {
                _url = config.filePath + 'store/listparts.aspx?model=' + encodeURIComponent(modelValue);
            }
        }
    	
        function cmdButtonClick(event)
        {
            if (_url !='' && elem.hasClass('selectorbtn')){
	        window.location = _url ;	
	    }
        }
    }
    $.fn.threestepmemoryselector = function(options)
    {
        return this.each(function()
        {
            var element = $(this);
            if(element.data('threestepmemoryselector')) return;
            var threestepmemoryselector = new ThreeStepMemorySelector(this, options);
            $(this).data('threestepmemoryselector', threestepmemoryselector);
        });
    };
})(jQuery);

/*********************************************************************
AJAX Memory Selector Base part Validator
************************************************/
(function($){
    var BPartMemSelectorValidator = function(element, options)
    {
        var elem = $(element);
        var obj = this;
        var defaults = {
            ddl1: null,
            ddl2: null,
            ddl3: null,
            cmdButton: null,
            stepName: 'RAMStep',
            basePartNo: '',
            memorySelector: true,
            filePath: '/',
            configView: 'Crucial',
            serverName :'/',
            ddl1Name: 'Select Manufacturer',
            ddl2Name: 'Select Product Line',
            ddl3Name: 'Select Model',
            cat: 'RAM'
        }
        var config = $.extend(defaults, options || {});
        var _ajaxRunning = false;
        var _url = '';
        var _ddl1 = config.ddl1;
        var _ddl2 = config.ddl2;
        var _ddl3 = config.ddl3;
        var _defaultWarningHtml = $('.notify-warning').html();
        
        emptyDDL( _ddl1, config.ddl1Name); 
        emptyDDL( _ddl2, config.ddl2Name); 
        emptyDDL( _ddl3, config.ddl3Name);
        _ddl1.mouseover(loadDDL1);
        _ddl1.change (loadDDL2);
        _ddl2.change (loadDDL3);
        _ddl3.change (loadDDL3Finish);
        elem.click (cmdButtonClick);
        elem.addClass('selectorbtnDisabled');
        
        this.SetCAT = function (cat) {
            config.cat = cat;
        }
        this.SetStepName = function (stepName) {
            config.stepName = stepName;
        }
        this.SetConfigView = function (configView) {
            config.configView = configView;
        }
        this.SetFilePath = function(filePath) {
            config.filePath = filePath;
        }
        this.Setddl1Name = function (ddl1Name) {
            config.ddl1Name = ddl1Name;
        }
        this.Getddl1Name = function () {
            return config.ddl1Name;
        }
        this.Setddl2Name = function (ddl2Name) {
            config.ddl2Name = ddl2Name;
        }
        this.Getddl2Name = function () {
            return config.ddl2Name;
        }
        this.Setddl3Name = function (ddl3Name) {
            config.ddl3Name = ddl3Name;
        }
        this.Getddl3Name = function () {
            return config.ddl3Name;
        }
        this.SetBasePartNo = function (basePartNo) {
            config.basePartNo = basePartNo;
        }
        this.GetBasePartNo = function () {
            return config.basePartNo;
        }    	
        this.SetMemorySelector = function (memorySelector) {
            config.memorySelector = memorySelector;
        }
        this.IsMemorySelector = function () {
            return config.memorySelector;
        }
        function emptyDDL(obj, defaulValue)
        {
            var options = '<option value="">' + defaulValue + '</option>';
            obj.html(options);
        }
        
        function SetActiveStep(nameExtn, stepId, totalCount)
	{
            var nameExtnId;
		
            for (i=1; i<= totalCount; i++)
            {
                nameExtnId ='#' + nameExtn+ i;
                if ($(nameExtnId).length > 0){
                    if (i == stepId){
                        $(nameExtnId).removeClass('label');
                        $(nameExtnId).addClass ( 'labelactive');
                    }
                    else{
                        $(nameExtnId).removeClass( 'labelactive');
                        $(nameExtnId).addClass( 'label');
                    }
                }
            }
            
            if (stepId > totalCount){
                elem.addClass('selectorbtn');
                elem.removeClass('selectorbtnDisabled');
            }
            else{
                elem.addClass('selectorbtnDisabled');
                elem.removeClass('selectorbtn');  
            }
        }
        function ajaxLoadDDL(url, ddl, ddlName)
        {
            $.ajax({
                url:url, dataType: 'html',
                beforeSend: function(x) {
                    if(x && x.overrideMimeType) {
                        x.overrideMimeType("application/j-son;charset=UTF-8");
                    }
                },
                success: function(data){
                    var eoptions = eval(data);
                    var options = '<option value="">' + ddlName + '</option>';
                    if (eoptions && eoptions.length && eoptions.length > 0) {
                        if (eoptions.length == 1 && eoptions[0].name =='N.A' ){
                            options += '<option value="(OTHERS)">All Models</option>'; 
                        }
                        else {
                            for (var i = 0; i < eoptions.length; i++) {
                                options += '<option value="' + eoptions[i].value + '">' + eoptions[i].name + '</option>';   
                            }
                        }
                    }
                    ddl.html(options);
                }
           });
        }
        function loadDDL1(e, obj)
        {            
            if (_ddl1.length <=2 && _ajaxRunning == false){
                _ajaxRunning= true;
                SetActiveStep(config.stepName, 1,3);
                emptyDDL( _ddl2,config.ddl2Name);
                emptyDDL( _ddl3,config.ddl3Name);
	        var url ='/ajax/_GetDropDownData.aspx';
	        url += '?DSName=mfgrbycat&cf=mfgr_code&df=mfgr_code&cat=' + config.cat + '&cv=' + encodeURIComponent(config.configView);	
	        ajaxLoadDDL(url, _ddl1, config.ddl1Name);	    
	        loadDDL2(e, _ddl2);
            }
        }
    	
        function loadDDL2(e, obj)
        {
            $('.notify-warning').hide();
            emptyDDL( _ddl3,config.ddl3Name); 
	    var mfgrValue =_ddl1.val();	
	    if (mfgrValue!= 'Select' && mfgrValue != 'Select Manufacturer' && escape(mfgrValue) != 'null' && mfgrValue != 'N.A' && mfgrValue!= '' && mfgrValue != config.ddl1Name){
                SetActiveStep(config.stepName, 2,3);
                emptyDDL( _ddl2,'Loading...');
	        var url ='/ajax/_GetDropDownData.aspx';
	        url += '?DSName=plbymfgr&cf=product_line_code&df=product_line_code&cat=' + config.cat + '&mfgr=' + encodeURIComponent(mfgrValue) + '&cv=' + encodeURIComponent(config.configView);
	        ajaxLoadDDL(url, _ddl2, config.ddl2Name);
	        loadDDL3(e, _ddl3);
            }
        }
        function loadDDL3(e, obj)
        {
            $('.notify-warning').hide();
            var mfgrValue =_ddl1.val();
            var plValue =_ddl2.val();
            if (mfgrValue!= 'Select' && mfgrValue != 'Select Manufacturer' && escape(mfgrValue) != 'null' && mfgrValue != 'N.A' && mfgrValue!= '' && mfgrValue != config.ddl1Name && plValue != 'Select' && plValue != 'Select Product Line' && escape(plValue) != 'null' && plValue != 'N.A' && plValue != config.ddl2Name && plValue !='')
            {
                SetActiveStep(config.stepName, 3,3);
                emptyDDL( _ddl3,'Loading...');
	        var url ='/ajax/_GetDropDownData.aspx';
	        url +='?DSName=modelbypl&cf=model_code&df=model_code&mfgr=' + encodeURIComponent(mfgrValue) + '&pl=' + encodeURIComponent(plValue) +'&cv=' + encodeURIComponent(config.configView);
	        ajaxLoadDDL(url, _ddl3, config.ddl3Name);
	    }
        }
        function loadDDL3Finish(event)
        {
            SetActiveStep(config.stepName, 4,3);
        }
        function cmdButtonClick(event)
        {
            var mfgrValue =_ddl1.val();
            var plValue =_ddl2.val();
            var modelValue =_ddl3.val();
            if (mfgrValue!= 'Select' &&  escape(mfgrValue) != 'null' && mfgrValue != 'N.A' && mfgrValue!= '' && mfgrValue != config.ddl1Name && plValue != 'Select' &&  escape(plValue) != 'null' && plValue != 'N.A' && plValue != config.ddl2Name && plValue !='' && modelValue != 'Select' &&  escape(modelValue) != 'null' && modelValue != 'N.A' && modelValue != config.ddl2Name && modelValue !='')
            {
                var url ='/ajax/_GetDropDownData.aspx';
                url +='?DSName=modeldetailparts&cf=INT_PART_NO&df=MODEL_TO_PART_OID&mfgr=' + encodeURIComponent(mfgrValue) + '&mdl=' + encodeURIComponent(modelValue) + '&cv=' + encodeURIComponent(config.configView);	
                $.ajax({url:url,dataType: 'html', 
                    beforeSend: function(x) {
                        if(x && x.overrideMimeType) {
                            x.overrideMimeType("application/j-son;charset=UTF-8");
                        }
                    },
                    success: function(data){
                        var eoptions = eval(data);
                        var mtbpSuccess = false;
                        if (eoptions && eoptions.length && eoptions.length > 0){
                            for (var i = 0; i < eoptions.length; i++) {
                                if (eoptions[i].value == config.basePartNo) {
                                    _url ='mpartspecs.aspx?mtbpoid=' + eoptions[i].name;
                                }
                            }
                            if (_url !=''){
                                window.location = _url ;
                            }
                            else{
                                var msghtml = _defaultWarningHtml;
                                msghtml = msghtml.replace('[BASE_PART_NO]', config.basePartNo);
                                msghtml = msghtml.replace('[MODEL]', modelValue);
                                msghtml = msghtml.replace('[LINK]', 'listparts.aspx?model=' + encodeURIComponent(modelValue));
                                $('.notify-success').hide();
                                $('.notify-warning').html(msghtml);
                                $('.notify-warning').show();
                            }
                        }
                    }
                });
            }
        }
    }
    $.fn.bpartmemselectorvalidator = function(options)
    {
        return this.each(function(){
            var element = $(this);
            if(element.data('bpartmemselectorvalidator')) return;
            var bpartmemselectorvalidator = new BPartMemSelectorValidator(this, options);
            $(this).data('bpartmemselectorvalidator', bpartmemselectorvalidator);
        });
    };
})(jQuery);



	

/*********************************************************************
Ajax Currency Convertory
*********************************************************************/
function AjaxCurrencyConvertor (url, resultDiv){
    var _url = url;
    var _resultDiv = resultDiv;

    $.ajax({
        url: _url,
        success: function(data) {
            $('.' +_resultDiv).html(data);
        }
    });
}

/************************************************************************
*List Parts selector
******************************************************************/

(function($){
    var ListPartsSelector = function(element, options)
    {
        var elem = $(element);
        var obj = this;
        var defaults = {
            expanded: false
        };
        var config = $.extend(defaults, options || {});
                
        this.ToggleLPProducts = function(flag, type){
            if (flag == 'ALL'){
                $("#recommend_"+ type).hide();
                $(".allparts_" + type).show();
                $(".allpartsfilter_" + type).show();
                $("input[type='slider']").each(function(){$(this).slider('resize')});
            }
            else {
                $("#recommend_"+ type).show();
                $(".allparts_" + type).hide();
                $(".allpartsfilter_" + type).hide();
            }
        }
        
        var GetType = function(obj){
            var id = obj.id;
            return id.substring(id.indexOf('_')+1);
        }
        
        $(".productoptions input").click(function(){
            var type = GetType(this);
            if($(this).is(':checked')) {
	        $(".span_" + type).show();
            }
            else {
	        $(".span_" + type).hide();
            }
        });
        $(".productoptions input").each(function(){
            var type = GetType(this);
            if($(this).is(':checked')) {
                $(".span_" + type).show();
            }else {
                $(".span_" + type).hide();
            }
         });
        
        $(".showallproduct").click(function(){
            obj.ToggleLPProducts ('ALL', GetType(this));
            return false;    	
        });
        $(".shopbyfilter").change(function(){
            var id =this.id;
            var sbvalue =$('#' + id +' option:selected').attr('name');
            var type = GetType(this);
            if (sbvalue == 'All Parts'){
                obj.ToggleLPProducts ('ALL', type);
            } else if (sbvalue == 'PriceLow'){
                $('.allparts_memory > div.part, .allparts_memory > div.partalt').sortElements(function(a,b){
                    var aVal = $.trim($(a).find('div.finalprice').text()).match(/\d*\.\d*/);
                    var bVal = $.trim($(b).find('div.finalprice').text()).match(/\d*\.\d*/);
                    return parseFloat(aVal) > parseFloat(bVal) ? 1 : -1;
                });
            } else if (sbvalue == 'PriceHigh'){
                $('.allparts_memory > div.part, .allparts_memory > div.partalt').sortElements(function(a,b){
                    var aVal = $.trim($(a).find('div.finalprice').text()).match(/\d*\.\d*/);
                    var bVal = $.trim($(b).find('div.finalprice').text()).match(/\d*\.\d*/);
                    return parseFloat(aVal) < parseFloat(bVal) ? 1 : -1;
                });
            }
            return false;
        });
        	
        $(".ptfilter").change(function(){            
            $('.ptfilter[id^="check_kitmemory"]').each(function(){
                var type = GetType(this);
                if($(this).is(':checked')) {
                    $(".cls" + type).show();
                } else {
                    $(".cls" + type).hide();
                }
            });
            $('.ptfilter[id^="check_denmemory"]').each(function(){
                var type = GetType(this);
                if(! $(this).is(':checked')) {
                    $(".cls" + type).hide();
                }
            });            
        });
        
        $('form').attr('autocomplete', 'off');
    };

    $.fn.listpartsselector = function(options)
    {
        return this.each(function()
        {
            var element = $(this);

            /* Return early if this element already has a plugin instance */
            if (element.data('listpartsselector')) return;

            /* pass options to plugin constructor */
            var listpartsselector = new ListPartsSelector(this, options);

            /* Store plugin object in this element's data */
            element.data('listpartsselector', listpartsselector);
        });
    };
})(jQuery);

/************************************************************************
*Single Drop Down Selector
*************************************************************************/

(function($){
    var SingleDDLMemorySelector = function(element, options)
    {
        var elem = $(element);
        var obj = this;
        var defaults = {
            ddl: 'select[name="ddlSingle"]',
            status: "div[name='memorySelectorStatus']",
            labelActive: "span.labelactive",
            stepName: 'RAMStep',
            cmdButton: "[name='cmdRAMStep']",
            basePartNo: '',
            memorySelector: true,
            configView: 'Crucial',
            serverName :'/',
            filePath: '/',
            ddlName: ['Select Category', 'Select Manufacturer','Select Product Line','Select Model'],
            selectorStepClass: 'selectorStep',
            cat: 'RAM',
            manufacturer: '',
            productLine: '',
            model: ''
        }
        var config = $.extend(defaults, options || {});
        var _initialLoad = false;
        var _url = '';        
        var _currentStep = 1;
        var _mfgrValue, _plValue, _modelValue;
        
        var _ddl1 = elem.children(config.ddl);
        var _statusDiv = elem.children(config.status);
        var _labelActive = elem.children(config.labelActive);
        var _cmdButton = elem.children(config.cmdButton);
        var _fourStep = false;
        if(config.cat == '')
        {
            _currentStep = 0;
            _fourStep = true;
        }
        else if(config.manufacturer != '')
        {
            _mfgrValue = config.manufacturer;
            var newsection = $("<div name='selectorStep_1' class='"+config.selectorStepClass+"'>1 &mdash; "+_mfgrValue+"</div>").click(backItUp);
            _statusDiv.append(newsection);
            _currentStep = 2;
            if(config.productLine != '')
            {
                _plValue = config.productLine;
                newsection = $("<div name='selectorStep_2' class='"+config.selectorStepClass+"'>2 &mdash; "+_plValue+"</div>").click(backItUp);
                _statusDiv.append(newsection);
                _currentStep = 3;
                if(config.model != '')
                {
                    _modelValue = config.model;
                    newsection = $("<div name='selectorStep_3' class='"+config.selectorStepClass+"'>3 &mdash; "+_modelValue+"</div>").click(backItUp);
                    _statusDiv.append(newsection);
                    _currentStep = 4;
                    _url = config.filePath + 'store/listparts.aspx?model=' + encodeURIComponent(_modelValue) + '&cat=' + encodeURIComponent(config.cat);
                    _labelActive.hide();
                    _ddl1.hide();
                    _cmdButton.show();
                }
            }
        }
        
        /*Init adds all teh events*/
        emptyDDL(_ddl1,config.ddlName[_currentStep]);
        _ddl1.mouseover(loadDDL1);
        _ddl1.mouseleave(function(e){e.stopPropagation();});
        _ddl1.change(loadDDL1Finish);
        _cmdButton.click(cmdButtonClick);
        if(_currentStep < 4)
        {
            _cmdButton.hide();
        }
        
        function emptyDDL(obj, defaulValue)
        {
            var options = '<option value="">' + defaulValue + '</option>';
            obj.html(options);
        }
        function loadDDL1(e, obj)
        {
            e.stopPropagation();
            if (!_initialLoad)
            {
                var url = config.serverName + 'ajax/_GetDropDownData.aspx';
                if(_currentStep==1){
                    url += '?DSName=mfgrbycat&cf=mfgr_code&df=mfgr_code&cat=RAM&cv=' + encodeURIComponent(config.configView);
                } else if(_currentStep==2){
                    url += '?DSName=plbymfgr&cf=product_line_code&df=product_line_code&cat=RAM&mfgr=' + encodeURIComponent(_mfgrValue) + '&cv=' + encodeURIComponent(config.configView);
                } else if (_currentStep == 3){
                    url +='?DSName=modelbypl&cf=model_code&df=model_code&mfgr=' + encodeURIComponent(_mfgrValue) + '&pl=' + encodeURIComponent(_plValue) +'&cv=' + encodeURIComponent(config.configView);
                }
                if(_currentStep > 0)
                {
                    ajaxLoadDDL(url, _ddl1, config.ddlName[_currentStep]);
                }
                else
                {
                    var options = '<option value="Select">' + config.ddlName[0] + '</option>';
                    options += '<option value="RAM">Memory</option>';
                    options += '<option value="SSD">Solid State Drive</option>';
                    _ddl1.html(options);
                }
                _initialLoad=true;
                _ddl1.unbind('mouseover', loadDDL1);
            }
        }
        function backItUp()
        {
            var newStep = $(this).attr('name').split('_')[1];
            if(_currentStep ==4)
            {
                _labelActive.show();
                _ddl1.show();
                _cmdButton.hide();
            }
            while(_currentStep > newStep)
            {
                _currentStep--;
                elem.find('div[name = "selectorStep_'+_currentStep+'"]').slideUp('fast', function(){$(this).remove();});
            }
            _labelActive.html('Step '+(_fourStep ? _currentStep + 1 : _currentStep)+'&mdash;');
            var url = config.serverName + 'ajax/_GetDropDownData.aspx';
            if(_currentStep==0){
                var options = '<option value="Select">' + config.ddlName[0] + '</option>';
                options += '<option value="RAM">Memory</option>';
                options += '<option value="SSD">Solid State Drive</option>';
                _ddl1.html(options);
            }
            else if(_currentStep==1){
                url += '?DSName=mfgrbycat&cf=mfgr_code&df=mfgr_code&cat=RAM&cv=' + encodeURIComponent(config.configView);
            }else if(_currentStep==2){
                url += '?DSName=plbymfgr&cf=product_line_code&df=product_line_code&cat=RAM&mfgr=' + encodeURIComponent(_mfgrValue) + '&cv=' + encodeURIComponent(config.configView);
            } else if (_currentStep == 3){
                url +='?DSName=modelbypl&cf=model_code&df=model_code&mfgr=' + encodeURIComponent(_mfgrValue) + '&pl=' + encodeURIComponent(_plValue) +'&cv=' + encodeURIComponent(config.configView);
            }
            if(_currentStep > 0)
            {
                ajaxLoadDDL(url, _ddl1, config.ddlName[_currentStep]);
            }
        }
        function loadDDL1Finish(event)
        {
            if (_ddl1.val()!= 'Select'){    
                var newSection = $('<div class="'+config.selectorStepClass+'" name="selectorStep_'+_currentStep+'" style="display:none;">'+(_fourStep ? _currentStep + 1 : _currentStep)+' &mdash; '+_ddl1.children("option:selected").text()+'</div>');
                
                var url = config.serverName + 'ajax/_GetDropDownData.aspx';
                if(_currentStep==0){
                    config.cat = _ddl1.val();
                    url += '?DSName=mfgrbycat&cf=mfgr_code&df=mfgr_code&cat=RAM&cv=' + encodeURIComponent(config.configView);
                }else if(_currentStep==1){
                    _mfgrValue = _ddl1.val();
                    url += '?DSName=plbymfgr&cf=product_line_code&df=product_line_code&cat=RAM&mfgr=' + encodeURIComponent(_mfgrValue) + '&cv=' + encodeURIComponent(config.configView);
                } else if (_currentStep == 2){
                    _plValue = _ddl1.val();
                    url +='?DSName=modelbypl&cf=model_code&df=model_code&mfgr=' + encodeURIComponent(_mfgrValue) + '&pl=' + encodeURIComponent(_plValue) +'&cv=' + encodeURIComponent(config.configView);
                } else if (_currentStep == 3){
                    _modelValue = _ddl1.val();
                }
                _currentStep++;
                if(_currentStep < 4){
                    ajaxLoadDDL(url, _ddl1, config.ddlName[_currentStep]);
                    _labelActive.html('Step '+(_fourStep ? _currentStep + 1 : _currentStep)+'&mdash;');
                    
                } else {
                    _labelActive.hide();
                    _ddl1.hide();
                    _cmdButton.show();
                    _url = config.filePath + 'store/listparts.aspx?model=' + encodeURIComponent(_modelValue) + '&Cat=' + encodeURIComponent(config.cat);
                }
                newSection.click(backItUp);
                _statusDiv.append(newSection);
                newSection.slideDown('fast');
            }
        }
        function ajaxLoadDDL(url, ddl, ddlName)
        {
            $.ajax({
                url:url,  dataType: 'html',
                beforeSend: function(x) {
                    if(x && x.overrideMimeType) {
                        x.overrideMimeType("application/j-son;charset=UTF-8");
                    }
                },
                success: function(data){
                    var eoptions = eval(data);
                    var options = '<option value="Select">' + ddlName + '</option>';
                    if (eoptions && eoptions.length && eoptions.length > 0) {
                        if (eoptions.length == 1 && eoptions[0].name =='N.A' ){
                            options += '<option value="(OTHERS)">All Models</option>'; 
                        }
                        else {
                            for (var i = 0; i < eoptions.length; i++) {
                                options += '<option value="' + eoptions[i].value + '">' + eoptions[i].name + '</option>';   
                            }
                        }
                    }
                    ddl.html(options);
                }
            });
        }
               
        function cmdButtonClick(event)
        {
            if (_url !=''){
                window.location = _url ;
            }
        }
    }
    $.fn.singleddlmemoryselector = function(options)
    {
        return this.each(function()
        {
            var element = $(this);
            if(element.data('singleddlmemoryselector')) return;
            var singleddlmemoryselector = new SingleDDLMemorySelector(this, options);
            $(this).data('singleddlmemoryselector', singleddlmemoryselector);
        });
    };
})(jQuery);

jQuery.fn.sortElements = (function(){
    var sort = [].sort;
    return function(comparator, getSortable) {
        getSortable = getSortable || function(){return this;};
        var placements = this.map(function(){
            var sortElement = getSortable.call(this),
                parentNode = sortElement.parentNode,
                /* Since the element itself will change position, we have
                 to have some way of storing its original position in
                 the DOM. The easiest way is to have a 'flag' node:*/
                nextSibling = parentNode.insertBefore(
                    document.createTextNode(''),
                    sortElement.nextSibling
                );
            return function() {
                if (parentNode === this) {
                    throw new Error(
                        "You can't sort elements if any one is a descendant of another."
                    );
                }
                /* Insert before flag:*/
                parentNode.insertBefore(this, nextSibling);
                /* Remove flag:*/
                parentNode.removeChild(nextSibling);
            };
        });
 
        return sort.call(this, comparator).each(function(i){
            placements[i].call(getSortable.call(this));
        });
    };
})();
/********************************************************************
* Collapse Expand Logic
********************************************************************/
function CrucialExpandCollapse(clsCollapse, clsExpand, collapseAll){
    $(document).ready(function() {
        if (collapseAll =='Y') {
            $("div." + clsCollapse).hide();
        } else {
            $("div." + clsCollapse).show();
            $("." + clsExpand + " a").addClass('open');
        }
        /*toggle the componenet with class msg_body*/
        $("." + clsExpand + " a").click(function(event){
            if ($(this).is('.open')) {
                $(this).parents().nextAll("div." + clsCollapse).slideUp(200);
                $(this).removeClass('open')
            } else {
                $(this).parents().nextAll("div." + clsCollapse).slideDown(200);
                $(this).addClass('open')
            }
            event.stopPropagation();
            return false;
        });
    });
}

/********************************************************************
* List Module memory Selector
********************************************************************/
(function($){
    var ListModuleMS = function(element, options)
    {
        var elem = $(element);
        var obj = this;
        var defaults = {};
        var config = $.extend(defaults, options || {});
        var _missingFilter = '';
        var _sort = 'PriceLow';
        
        this.updatePartList = function (){
            $('#filterProgress').show();
            var params = GetParams();       
            var url = $('#fil_filePath').val() +'ajax/_allModulePartList.aspx?' + params
            $('#partList').load(url, function() {
                $('#filterProgress').hide();
                $('div.shopbylist select').val($('div.shopbylist select option[name^="'+_sort+'"]').val());
                obj.sortParts($('div.shopbylist select')[0]);
            });
        }
    
        this.selectAllFilter = function (){			
            var prodType = $('#hidProdFamilyToggle').val();
            $(":checkbox[name^=filter"+prodType+']:checked"').each(function(){$(this).removeAttr("checked");});
            var density = $("#"+prodType+"density");
            var z = density[0].defaultValue.split(';');
            density.slider("value", z[0], z[1]);
            obj.updatePartList();
        }
        
        this.sortParts = function(select){
            _sort =$(select).children(':selected').attr('name');
            if (_sort == 'PriceLow'){
                $('#allPartsSpec > div.part, #allPartsSpec > div.partalt').sortElements(function(a,b){
                    var aVal = $.trim($(a).find('div.finalprice').text()).match(/\d*\.\d*/);
                    var bVal = $.trim($(b).find('div.finalprice').text()).match(/\d*\.\d*/);
                    return parseFloat(aVal) > parseFloat(bVal) ? 1 : -1;
                });
            } else if (_sort == 'PriceHigh'){
                $('#allPartsSpec > div.part, #allPartsSpec > div.partalt').sortElements(function(a,b){
                    var aVal = $.trim($(a).find('div.finalprice').text()).match(/\d*\.\d*/);
                    var bVal = $.trim($(b).find('div.finalprice').text()).match(/\d*\.\d*/);
                    return parseFloat(aVal) < parseFloat(bVal) ? 1 : -1;
                });
            }
        }
        
        /*set the default radion button*/
        $(".radioselected").attr("checked","checked");
        /*onload load the ajax*/
        obj.updatePartList(); 
        
        $("input.filtercheck:checkbox").click(function(){
            obj.updatePartList();
        });
        $("input.technology:radio").click(function(){
            var newTech = $(this).val().replace(/\s/g,'');
            var oldTech = $("input.technology.radioselected").val().replace(/\s/g,'');
            $("#pft"+oldTech).hide();
            $("#pft"+newTech).show();
            $("#pft"+newTech+" input[type='slider']").each(function(){$(this).slider('resize');});
            $("input.technology.radioselected").removeClass("radioselected");
            $(this).addClass("radioselected");
            obj.updatePartList();
        });
        $("select.shoppingtype").change(function(){
            var prodType = $(this).children('option:selected').val();
            window.location = escape($('#fil_filePath').val()) + "store/listmodule.aspx?Family=" + encodeURIComponent(prodType);
        });
        
        function errorMessage(type){
            _missingFilter += " " + type;
            $('#partList').hide();
            $('#missingParts').html("Please select at least one "+type);
            $('#missingParts').show();
        }
        function GetParams() {
            var prefix;
            var params = 'file_path=' + escape($('#fil_filePath').val());
            var prodType = $('#hidProdType').val();
            var tech =$("input[name='technology']:checked").val();
            var techNoSpace = tech.replace(/\s/g, '');
            prefix = 'filterpft' + tech + '|';

            params += '&' + 'filterSuffix=pft' + encodeURIComponent(tech);
            params += '&' + 'prodType=' +  encodeURIComponent(prodType);
            params += '&' + 'Family=' + encodeURIComponent(tech);


            params += '&' + encodeURIComponent(prefix) + 'PRODUCT_FAMILY|' + encodeURIComponent(tech) + '=' + encodeURIComponent(tech);

            $("input.filtercheck[checked]:checkbox").each(function() {
                var chkName;
                var chkVal;
                chkName =$(this).attr("name");
                if (chkName.indexOf("filterpft" + techNoSpace +"|") >=0) { 
                    chkName = chkName.replace('USBFLASHDRIVE', 'USB FLASH DRIVE');
                    chkVal=$(this).val();
                    params += '&' + encodeURIComponent(chkName) + '=' + encodeURIComponent(chkVal);
                }
            	
            });		
            return params;
        }
    }
    $.fn.listmodulems = function(options)
    {
        return this.each(function()
        {
            var element = $(this);

            /* Return early if this element already has a plugin instance*/
            if (element.data('listmodulems')) return;

            /* pass options to plugin constructor*/
            var listmodulems = new ListModuleMS(this, options);

            /* Store plugin object in this element's data*/
            element.data('listmodulems', listmodulems);
        });
    };
})(jQuery);


function showBookmarkableUrl(){
    var bookmarkUrl = BuildFilteredURL();
    if (bookmarkUrl.length > 1000){
        alert('Warning: too many filter options selected. Please clear some selections and try again.');
    }else{
        window.location = bookmarkUrl;
    }
}
function BuildFilteredURL()
{
    var bookmarkUrl;
    var filter = '';
    var filterSuffix = 'pft' + $('.technology:checked').val();
    var prefix = 'filter' + filterSuffix + '|';;
  
    $("input[name^="+prefix+"]:checked").each(function(){
        if($(this).val().length > 0)
        {
            filter += "~" + encodeURIComponent($(this).val()) + "~";
        }
    });
    bookmarkUrl = window.location.protocol + '//' + window.location.hostname + $('#fil_filePath').val() + 'store/listmodule/'; 
    bookmarkUrl += encodeURIComponent($('.technology:checked').val());
    if (filter.length > 0){
        bookmarkUrl += "/" + filter;
    }
    bookmarkUrl += "/list.html";      

    return bookmarkUrl;
}



function showHelpPopup(divID)
  {
    $("#" + divID).overlay({
        /*custom top position*/
        top: 200,
        /* some mask tweaks suitable for facebox-looking dialogs*/
        mask: {
          /* you might also consider a "transparent" color for the mask*/
          color: '#fff',
          /* load mask a little faster*/
          loadSpeed: 200,
          /* very transparent*/		opacity: 0.9
        },
        /* disable this for modal dialog-type of overlays*/
      closeOnClick: false,
      /*  load it immediately after the construction*/
      load: true
    });
  }
  
function GetParams() {
    var prefix;
    var params = 'file_path=' + escape($('#fil_filePath').val());
    var prodType = $('#hidProdType').val();
    var tech =$("input[name='technology']:checked").val();
    var modelName = escape($('#fil_model_name').val());
    var techNoSpace = '';
    if(tech)
    {
        tech.replace(/\s/g, '');
        prefix = 'filterpft' + tech + '|';

        params += '&' + 'filterSuffix=pft' + encodeURIComponent(tech);
        params += '&' + 'prodType=' +  encodeURIComponent(prodType);
        params += '&' + 'Family=' + encodeURIComponent(tech);
    

        params += '&' + encodeURIComponent(prefix) + 'PRODUCT_FAMILY|' + encodeURIComponent(tech) + '=' + encodeURIComponent(tech);

        $("input.filtercheck[checked]:checkbox").each(function() {
            var chkName;
            var chkVal;
            chkName =$(this).attr("name");
            if (chkName.indexOf("filterpft" + techNoSpace +"|") >=0) { 
                chkName = chkName.replace('USBFLASHDRIVE', 'USB FLASH DRIVE');
                chkVal=$(this).val();
                params += '&' + encodeURIComponent(chkName) + '=' + encodeURIComponent(chkVal);
            }
        	
        });	
    }
    else if (modelName != 'undefined')
    {
        modelName = modelName.replace('+','%2B');
        modelName = modelName.replace('%B5','%u00b5');
        params += '&model=' + modelName;
    }
    return params;
}

function rssURL(newURL)
{
    var params = GetParams();
    var feedURL = $('#hidRSSURL').val() + params;
    
    if (feedURL.length > 0 && newURL.length > 0){
        if (newURL == '{0}'){
          newURL =feedURL;
        }else{
          newURL =newURL.replace('{0}',escape(feedURL));
        }
        window.location = newURL;
        return true;
    }
}

function showElement(elem)
{
    $('#'+elem).show();
    return false;
}

function hideElement(elem)
{
    $('#'+elem).hide();
    return false;
}

function getQueryParams(){
    var queryString = {};
    window.location.href.replace(
        new RegExp("([^?=&]+)(=([^&]*))?", "g"),
        function($0, $1, $2, $3) { queryString[$1] = $3; }
    );
    return queryString;
}
