function ieUpgradeCheck(){
    if (jQuery.browser.msie) {
        if (parseInt(jQuery.browser.version) < 7.0) {
        	if ($.cookie("allowIE6") != "1") {
            	document.location = '/wcsstore/CVB2BDirectStorefrontAssetStore/content/ie6_upgrade.html';
        	}
        }
    }
}

(function(){
	if (window.location.pathname != '/webapp/wcs/stores/servlet/DiamondPageRequestFormView?catalogId=10551&langId=-1&storeId=10151') {
		ieUpgradeCheck();
	}
})();

//test if jjk namespace exists
if(window["JJK"] == null) {
	JJK = {};
}

JJK.util = {
	
	itemChanged: function(flag, persPage) {
		
		if(flag == 'P'){
			document.getElementById('addToCartBtn').href = persPage;
		}
		else{
			document.getElementById('addToCartBtn').href = 'javascript: ajaxAdd2MiniCartAndShopCart(document.addItems)';
		}
	},
	
	populateBillStates:function( countryFieldName, statesFieldName, tabindex){
		$('#addrErrors').hide();
		
		//take parent form of the country select box (assume there are no nested forms)
		var form = $(":input[name="+countryFieldName+"]").parents("form");
		var selectedCountryCode=form.find(":input[name="+countryFieldName+"]").val(); 
		
		this.populateStates(selectedCountryCode, statesFieldName, form, tabindex);
	},
	
	populateStates:function(selectedCountryCode, statesFieldName , form, tabindex){
		
		var tabindexattr = (undefined == tabindex) ? '' : ' tabindex="'+tabindex+'" ';
		
		var ajaxOptions = {
				type: "POST",
				url: "CVProcessAddress",
				dataType: "json",
				data: "countryCode="+selectedCountryCode,
				success: function(json)
				{
					var response = json.JSON;
					var stateToBePopulated = form.find(':input[name="'+statesFieldName+'"]'); //use ":input" instead of "select "because can be input and select box
					
					if($(stateToBePopulated).attr('type') == 'hidden') {
		                stateToBePopulated = $(stateToBePopulated).parent();
		            }
					
					//if there are CSS classes assigned to input box we need to copy it
					var classPlaceholder = "";
					var cssClasses = stateToBePopulated.attr("class");
					if(cssClasses){
					    classPlaceholder='class="'+stateToBePopulated.attr("class")+'"';
					}
					
					if( response[0] == null){
						stateToBePopulated.replaceWith('<input type="text" name="' + statesFieldName +'" maxlength="49" size="40" value="" ' + classPlaceholder +' onblur="javascript:trimMe(this)"'+ tabindexattr + '/>');
					}else{
						var selectHtml = '<div class="select" name="' + statesFieldName + '"' + tabindexattr + '><div class="options-list"><ul class="options">';
						selectHtml += '<li class="option" v="">Please Select</li>';
		                for(var i=0; response[i] != null; i++)
		                {
		                    var stateProvince = response[i];
		                    selectHtml += '<li class="option" v="' + stateProvince[0] + '">' +stateProvince[1] + '</li>';
		                }
		                
		                selectHtml += '</ul></div></div>';
		                stateToBePopulated.replaceWith(selectHtml);
		                
		                prepareSelect(form.find(' div.select[name="'+statesFieldName+'"]'));
					}
				}
			}	
			$.ajax(ajaxOptions);
	}
};

function showModal(personalizationUrl){
	
	var src = 'https://' + location.host + '/webapp/wcs/stores/servlet/'+ personalizationUrl;
	$.modal('<iframe src="' + src + '" height="563" width="758" style="border:0" name="modalFrame">', {
		closeHTML:"",
		containerCss:{
			backgroundColor:"#fff",
			borderColor:"#0063dc",
			height:563,
			padding:0,
			width:758
		},
		overlayClose:true,
		close:true
	});
}

/*error handling helper functions start*/
function addErrorClassToFields(){
    var items = $(".error-validate-msg");
    $.each(items, function (i,item){
        var inputElName = $(item).attr("id").replace("Err","");
        if($.trim($(item).text())!=""){//don't add if it's just placeholder for error message without actual message
            var inputEl = $('[name='+inputElName+']');
            if(inputEl && inputEl.length>0){
                inputEl.addClass("error-validate-msg");
            }
        }
     });
}

function addErrorClassToField(inputElParam){
    var inputEl = (typeof inputElParam == "object")?inputElParam:$('[name='+inputElParam+']');
    if(inputEl && inputEl.length>0){
        inputEl.addClass("error-validate-msg");
    }
}

function removeErrorClassFromField(inputElParam){
    var inputEl = (typeof inputElParam == "object")?inputElParam:$('[name='+inputElParam+']');
    if(inputEl && inputEl.length>0){
        inputEl.removeClass("error-validate-msg");
    }
}

function displayError(inputEl, errorMsgEl, message){
    if(inputEl && inputEl.length>0){
        inputEl.addClass("error-validate-msg");
    }
    if(errorMsgEl && errorMsgEl.length>0){
        errorMsgEl.addClass("error-validate-msg");
        errorMsgEl.show();
        errorMsgEl.html(message);
    }
}

function hideError(inputEl, errorMsgEl){
    if(inputEl && inputEl.length>0){
        inputEl.removeClass("error-validate-msg");
    }
    if(errorMsgEl && errorMsgEl.length>0){
        errorMsgEl.removeClass("error-validate-msg");
        errorMsgEl.hide();
        errorMsgEl.html('');
    }
}
/*error handling helper functions end*/

/*helper methods for firebug debugging start*/
function writeConsoleError(errorMessage){
    window.console && console.warn(errorMessage);
}
	  
function writeConsoleDebug(debugMessage){
    try {
    	typeof debug !== 'undefined' && (debug==true) && window.console && console.debug(debugMessage);
    } catch(err) {}
}
/*helper methods for firebug debugging end*/

function popUpBig(URL,width,height, params) {
    var defaultParams = 'toolbar=0,scrollbars=0,location=0,statusbar=1,menubar=0,resizable=1';
    var left   = (screen.availWidth  - width)/2;
    var top    = (screen.availHeight - height)/2;
    var position = 'left = '+left+',top = '+top;
    
    params = (typeof params ==='undefined')? defaultParams: params;
    day = new Date();
    id = day.getTime();
    eval("page" + id + " = window.open(URL, '" + id + "', 'width=" + width + ",height=" + height +", " +params+ "," +position+ " ');");
}

function getMessage(bundle, key, params){
    var message = bundle[key];
    if(params){
        for(var i=0; i<params.length; i++){
            message = message.replace("{"+i+"}", params[i]);
        }
    }
    return message;
}

Array.prototype.remove = function(from, to) {
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
};  

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}

/*This function call will make links non secured*/
function makeLinksNonSecured() {
	var hostName = window.location.hostname;
	var pathName = window.location.pathname;
	pathName = pathName.substring(0,pathName.lastIndexOf("/"));
	
	var pathFullQualifier = "http://"+ hostName + pathName + "/" ;
	var hostQualifier =  "http://"+ hostName ;
	var tempvar = "";
   	$("a").each(function(i) {
		if($(this).attr("href") === undefined || $(this).attr("href") == "")
		{
			 // it does not have any link associated...Don't do any thing  
		}
		else if ( (  /^(http|ftp|https):\/\/.*$/i.test($(this).attr("href")) ) 								//If link starts with HTTP/HTTPS/FTP/Javascript/# then do not touch it
		        || ( /^mailto:.*$/i.test($(this).attr("href")) )                                        //if link starts with mailto then do not touch it
		   	|| ( /^(javascript).*$/i.test( $(this).attr("href") ) || (($(this).attr("href") !== undefined) && $(this).attr("href").replace(/^\s+|\s+$/, '').indexOf('#' ) == 0 )) )
		{
			// Don't do any thing 
		}
		else if ( ($(this).attr("href") !== undefined) && ($(this).attr("href").indexOf("/") == 0))		//If link starts / which is absolute path with out host then add the host name
		{
			$(this).attr("href" ,  hostQualifier +   $(this).attr("href"));
		}
		else																							 	//else make path as relative path
		{
			tempvar = tempvar + " " + $(this).attr("href") + "\n" ;
			$(this).attr("href" ,     pathFullQualifier +   $(this).attr("href"));
		}
   });
};

/*for search box start*/
function checkForEnterKeyHead(e) {
	var charCode;
	if(e && e.which){
	        charCode = e.which;
	}else if(window.event){
	        e = window.event;
	        charCode = e.keyCode;
	}
	if(charCode == 13) {
	  setSelectedCategoryInHead();
	  return false;
	}
}

function setSelectedCategoryInHead () {
	document.CatalogSearchForm.selectedCategory.value = $('div.select#categoriesId input').val();
	document.CatalogSearchForm.searchOperationSelected.value = "search";
	document.CatalogSearchForm.submit();
}

function setQuickOrderSearch (form) {
	document.CatalogSearchForm.selectedCategory.value = $('div.select#categoriesId input').val();
	document.CatalogSearchForm.searchOperationSelected.value = "quickorder";
	document.CatalogSearchForm.submit();
}
/*for search box end*/
JJK.promo = {
    checkPromoCode: function(promoCode) {
		var promoCode = promoCode;
        if (promoCode!=undefined && promoCode!="") {
            if (!this.checkCookie("PromoCode"))
                this.setCookie('PromoCode',promoCode,7);
        }
    },
    
    checkUrl: function ( name ) {
      name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
      
      var regexS = "";
      
      if(name == 'PromoCode'){
        var regexS = "[\\?&]"+name+"=([^&#]*)";
      }
      else if(name == 'pc-'){
         var regexS = "[_]"+name+"([^&#]*)";
      } 
      var regex = new RegExp( regexS );
      //SF 5018
      var NoMMC_URL=cmRemoveParameter("cm_mmc_o",window.location.href); 
      // end SF 5018
      var results = regex.exec(NoMMC_URL);
      
      if( results == null || results[1] == "undefined" )
        return "";
      else
        return results[1];
    },
    
    checkCookie: function (cn) {
        var pc=this.getCookie(cn);
        if (pc!=null && pc!="" && pc != "undefined") {
            return true;
        }
        else {
            return false;
        }
    },
    
    getCookie: function (c_name) {
        if (document.cookie.length>0) {
            c_start=document.cookie.indexOf(c_name + "=");
            if (c_start!=-1) { 
                c_start=c_start + c_name.length+1 ;
                c_end=document.cookie.indexOf(";",c_start);
                if (c_end==-1) c_end=document.cookie.length
                    return unescape(document.cookie.substring(c_start,c_end));
            } 
        }
        return ""
    },
    
    setCookie: function (c_name,value,expiredays) {
        var exdate=new Date();
        var newvalue = "";
        if(value != "undefined")
        {
        	newvalue = value;
        }
        exdate.setDate(exdate.getDate()+expiredays);
        document.cookie=c_name+ "=" +escape(newvalue)+((expiredays==null) ? "" : "; expires="+exdate.toGMTString());
    },
    
    Delete_Cookie: function ( name, path, domain ) {
        if ( this.Get_Cookie( name ) ) document.cookie = name + "=" +
        ( ( path ) ? ";path=" + path : "") +
        ( ( domain ) ? ";domain=" + domain : "" ) +
        ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
    },
    
    Get_Cookie: function ( check_name ) {
        // first we'll split this cookie up into name/value pairs
        // note: document.cookie only returns name=value, not the other components
        var a_all_cookies = document.cookie.split( ';' );
        var a_temp_cookie = '';
        var cookie_name = '';
        var cookie_value = '';
        var b_cookie_found = false; // set boolean t/f default f
    
        for ( i = 0; i < a_all_cookies.length; i++ )
        {
            // now we'll split apart each name=value pair
            a_temp_cookie = a_all_cookies[i].split( '=' );
    
    
            // and trim left/right whitespace while we're at it
            cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
    
            // if the extracted name matches passed check_name
            if ( cookie_name == check_name )
            {
                b_cookie_found = true;
                // we need to handle case where cookie has no value but exists (no = sign, that is):
                if ( a_temp_cookie.length > 1 )
                {
                    cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
                }
                // note that in cases where cookie is initialized but no value, null is returned
                return cookie_value;
                break;
            }
            a_temp_cookie = null;
            cookie_name = '';
        }
        if ( !b_cookie_found )
        {
            return null;
        }
    }
}

$(document).ready(function () {
    //it is very important to place def of hoverClass before use!!! => before: $("#cat-nav li").hoverClass("sfHover").css("zIndex:9999");--%>
    $.fn.hoverClass = function(c) {
        return this.each(function(){
             $(this).hover(
                 function() { $(this).addClass(c);  },
                 function() { $(this).removeClass(c); }
             );
         });
    };
    $("#cat-nav li").hover(
            function(){ $("ul", this).fadeIn("fast"); },
            function() { }
    );
    if (document.all) {
        $("#cat-nav li").hoverClass("sfHover").css("zIndex:9999");
    }
    //This function call will make links non secured
    makeLinksNonSecured();
    
   //JJK.promo.checkPromoCode();
});

function submitEmail(emailId, url, ahrefId, defaultValue){
    var email = $("#"+emailId).val();
    var re = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/;
    if (email != defaultValue && email != 'Enter Valid Email Address' && re.test(email)) {
        url += email;
    } else {
    	$("#"+emailId).val('Enter Valid Email Address');
    	return false;
    }
    
    $("#"+ahrefId).attr("href", url); 
    $("#"+emailId).val(defaultValue);
}

//SF 5018
function cmRemoveParameter (parameter, inString) {
    if (cmIndexOfParameter(parameter, inString) == -1) {
        return inString;
    }
	var s = inString;
	var begin = s.indexOf(parameter);
	var start = (begin - 1);
	var end = s.indexOf("&", begin);
	if (end == -1) {
		end = s.length;
	}
	if (s.substring(start, begin) == "?") {    // retain leading "?"
		start = (start + 1);
		end = (end + 1);
	}
	return s.substring(0, start) + s.substring(end, s.length);
}
// end SF 5018
