/**
* @fileoverview ebiz.js: A module used for client specific functionality
*
* This module defines a single symbol named "Venda.Ebiz"
* all ebiz utility functions are stored as properties of this namespace
* functions that are spacific this site shoudl be added to this file only.
*/

//Declare namespace for ebiz
Venda.namespace("Ebiz");

 /**
 * The following global variables (directly below) are NEEDED to support legacy javascript functions - DO NOT REMOVE! see RT#113376 for more details.
 * 1. shown
 * 2. hidden
 */

var shown = new Image();
shown.src = "/venda-support/images/bulleton.gif";
var hidden = new Image();
hidden.src = "/venda-support/images/bulletoff.gif";

 /**
 * Split a string so it can be displayed on multiple lines so it does not break display layout - used on order confirmation and order receipt page
 * @param {string} strToSplit string that needs to be split 
 * @param {Integer} rowLen length of row which will hold the string
 * @param {string} displayElem the html container which will display the splitted string
 */
Venda.Ebiz.splitString = function(strToSplit, rowLen, dispElem) {
	var stringlist = new Array();
	while (strToSplit.length > rowLen) {
	   stringlist.push( strToSplit.slice(0,rowLen));
	   strToSplit=strToSplit.substr(rowLen);
	}
	if (strToSplit.length) {
		stringlist.push(strToSplit);
	}
	document.getElementById(dispElem).innerHTML = stringlist.join('<br>');
};

 /**
 * A skeleton function for validating user extened fields - needs to be amended by the build team
 * @param {object} frmObj HTML form containing user extended field elements
 */
Venda.Ebiz.validateUserExtendedFields = function(frmObj) {
	if(frmObj) {
		if ( (frmObj.usxtexample1.checked==false) && (frmObj.usxtexample2.checked==false) && (frmObj.usxtexample3.checked==false))  {	
			alert("Please tick at least one checkbox");
			return false;
		}			
		return true;		
	} 
	return false;
};

//Declare namespace for bklist
Venda.namespace("Ebiz.BKList");
Venda.Ebiz.BKList.jQuery = jQuery; 
Venda.Ebiz.BKList.configBKList = {
		bklist: "",
		divArray: ['#sortby','.sort_results', '.searchpsel', '.pagn', '.refinelist'],
		removeDivArray:['.categorytree'],
		enableBklist: true
};
/**
* Sets the config values to each config type
* @param {string} configType this is an configuration type name
* @param {array} settings this is the value of each configuration type
*/

Venda.Ebiz.BKList.init = function(settings) {
	for (var eachProp in settings) {
		this.configBKList[eachProp] = settings[eachProp];
	}
};
Venda.Ebiz.BKList.jQuery(document).ready(function() {
	if(Venda.Ebiz.BKList.configBKList.enableBklist){
		Venda.Ebiz.BKList.ChangeLink();
	}
});

Venda.Ebiz.BKList.getUrl = function(){
	var curUrl = document.location.href; 
	if(curUrl.indexOf("&amp;") != -1){
		 curUrl = curUrl.replace(/&amp;/gi,'&');		
	}
	return Venda.Platform.getUrlParam(curUrl, "bklist");
}

Venda.Ebiz.BKList.ChangeLink = function(){
var divArray = Venda.Ebiz.BKList.configBKList.divArray;  
var removeDivArray = Venda.Ebiz.BKList.configBKList.removeDivArray;  
var bklist = Venda.Ebiz.BKList.configBKList.bklist || Venda.Ebiz.BKList.getUrl() || "";
var strBklist = "&bklist";
	if (bklist != "") {
		var addBklist =  strBklist + "=" + bklist;
		for (var i = 0; i < divArray.length; i++) {

			if(Venda.Ebiz.BKList.jQuery(divArray[i]+ " a").attr("href")){
				Venda.Ebiz.BKList.jQuery(divArray[i]+ " a").attr("href", function() {		
					return Venda.Ebiz.BKList.jQuery(this).attr("href") + addBklist; 			
				});	
			}
			
			if(Venda.Ebiz.BKList.jQuery(divArray[i] + " option").attr("value")){
				Venda.Ebiz.BKList.jQuery(divArray[i] + " option").attr("value", function() {	
					return Venda.Ebiz.BKList.jQuery(this).attr("value") + addBklist; 
				});				
			}
		}	
		
		for (var i = 0; i < removeDivArray.length; i++) {
			Venda.Ebiz.BKList.jQuery(removeDivArray[i]+" a").attr("href", function() {
				var currentLink = Venda.Ebiz.BKList.jQuery(this).attr("href");
				var newLink = currentLink;
				if (newLink.length > 2) {
					if (currentLink.indexOf("&bklist=") != -1) {
						newLink = currentLink.substring(0, currentLink.indexOf("&bklist="));
					}
					if (newLink.indexOf("&view=") != -1) {
						newLink = newLink.substring(0, newLink.indexOf("&view="));
					}
				}
				return newLink;
			});
		}
		if(Venda.Ebiz.BKList.jQuery("#tag-pageSearchurlFull")){
			var newUrl = Venda.Ebiz.BKList.jQuery("#tag-pageSearchurlFull").text()+ addBklist ;
			Venda.Ebiz.BKList.jQuery("#tag-pageSearchurlFull").text(newUrl);
		}
		if(Venda.Ebiz.BKList.jQuery("#tag-pageSearchurl")){
			var newUrl = Venda.Ebiz.BKList.jQuery("#tag-pageSearchurl").text()+ addBklist ;
			Venda.Ebiz.BKList.jQuery("#tag-pageSearchurl").text(newUrl);
		}		
		if(Venda.Ebiz.BKList.jQuery("#tag-pageIcaturl")){
			var newUrl = Venda.Ebiz.BKList.jQuery("#tag-pageIcaturl").text()+ addBklist ;
			Venda.Ebiz.BKList.jQuery("#tag-pageIcaturl").text(newUrl);
		}			
	}
}


/**
 * A pagination style 4, that is press "Enter" on key borad to redirect to search page
 */
Venda.Ebiz.changePage =function(page,curpage,ptotal,pitem){
	var pageurl = "";
	var param1 = "";
	var pageAlert = document.getElementById("tag-pageAlert").innerHTML;
	var pageurlSearch = document.getElementById("tag-pageSearchurl").innerHTML;
	if(pageurlSearch != ""){
		pageurl = document.getElementById("tag-pageSearchurlFull").innerHTML;
		param1 = "&setpagenum=";
	}else {
		pageurl = document.getElementById("tag-pageIcaturl").innerHTML;
		param1 = "&curpage=";
	}
	var validnum=/(^-?[1-9](\d{1,2}(\,\d{3})*|\d*)|^0{1})$/;
	pagenum = parseInt(page.value);
	ptotalnum = parseInt(ptotal);
	if(validnum.test(page.value) && page.value > 0){
		if(page.value == curpage){
			page.value = curpage;
		}else if((pagenum <= ptotalnum) && (page.value != curpage)){
			pageurl = pageurl + param1 + page.value + '&' + pitem;
			window.location = pageurl;			
		}else{
			alert(pageAlert);
			page.value = curpage;
		}
	}else{
		alert(pageAlert);
		page.value = curpage;
	    return false;		
	}

};

Venda.Ebiz.CookieJar = new CookieJar({expires: 3600 * 24 * 7, path: '/'});	

jQuery.fn.popupIframe = function(){
	if ( jQuery.browser.msie && /6.0/.test(navigator.userAgent) ) {
	var src   = 'javascript:false;';
	  html = '<iframe class="popupIframe" src="'+src+'" style="-moz-opacity: .10;filter: alpha(opacity=1);height:expression(this.parentNode.offsetHeight+\'px\');width:expression(this.parentNode.offsetWidth+\'px\');'+'"></iframe>';
		if (jQuery('.popupIframe').length == 0 ){
			this.prepend(html);
		}
	 }
};

/**
* swapvideo is using for swap video file - used on scat/videoshowcase
* @param (string) videoID is element that contain data
* @param (string) targetTitle is target to set title that get from videoID
* @param (string) targetDesc is target to set description that get from videoID
* @param (string) targetPlayer is target to set viedo player that get from videoID
*/
Venda.Ebiz.swapvideo=function(videoID,targetTitle,targetDesc,targetPlayer,basePath,file){
  var videoURL=basePath+jQuery("#"+videoID+" .video").html();
  var videoDESC=jQuery("#"+videoID+" .detail").html();
  var videoTITLE=jQuery("#"+videoID+" .title").html();
  jQuery("#"+targetDesc).html(videoDESC);
  jQuery("#"+targetTitle).html(videoTITLE);
  jQuery("#"+targetPlayer).html('<object id="player" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" name="player" width="480" height="295"><param name="movie" value="'+ basePath + 'player-licensed.swf" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="flashvars" value="file=' + basePath + file + '&autostart=true" /><embed type="application/x-shockwave-flash" id="'+ videoID + '" name="' + videoTITLE + '" src="' + basePath + 'player-licensed.swf"  width="480"  height="295" allowscriptaccess="always"  allowfullscreen="true" repeat="none" flashvars="file=' + basePath + file + '&autostart=true"/></object>');
};


/**
* Host from Youtube : swapvideo is using for swap video file - used on scat/videoshowcase
* @param (string) videoID is element that contain data
* @param (string) targetTitle is target to set title that get from videoID
* @param (string) targetDesc is target to set description that get from videoID
* @param (string) targetPlayer is target to set viedo player that get from videoID
* @param (string) vkink is a youtube url
*/
Venda.Ebiz.swapvideoYoutube=function(videoID,targetTitle,targetDesc,targetPlayer,vlink){
  var videoURL=vlink;
  var videoDESC=jQuery("#"+videoID+" .detail").html();
  var videoTITLE=jQuery("#"+videoID+" .title").html();
  jQuery("#"+targetDesc).html(videoDESC);
  jQuery("#"+targetTitle).html(videoTITLE);
  jQuery("#"+targetPlayer).html('<object width="528" height="325"><param name="movie" value="'+vlink+'&amp;hl=en_US&amp;fs=1&amp;autoplay=0"></param><param name="wmode" value="transparent"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="'+vlink+'&amp;hl=en_US&amp;fs=1&amp;autoplay=0" wmode="transparent" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="528" height="325"></embed></object>');
};




/**
 * The basic dialog - can show the contents from URL/ DIV ids.
 * It will be rendered from a html starts with "doDialog" classname.
 */
Venda.namespace("Ebiz.PopupDialog");
jQuery(document).ready(function() {
	jQuery("body").append("<div id=\"mainDialog\"><div class=\"loadingImg\"></div><div id=\"contentDialog\"></div></div>");
	jQuery(this).find("[class*=doDialog]").bind("click", function() {
		var defaultSetting = {
			modal: true,
			autoOpen: false,
			closeOnEscape: true,
			width: 450,
			resizable: false,
			draggable: false,
			zIndex: 1,
			hide: "blind",
			position: "center",
			buttons: {
				Close: function() {Venda.Ebiz.PopupDialog.closeDialog();}
			},
			containerID: ""
		};
		
		var _tmp = Venda.Ebiz.PopupDialog.getSettings(this);
		if (_tmp != null) {
			var each = _tmp.split(",");
			for(var i = 0; i < each.length; i++){
				var elem = each[i].split(":");
				if(defaultSetting[elem[0]] != null) {
					defaultSetting[elem[0]] = elem[1];
				}
			}
		}
		jQuery("#mainDialog").dialog(defaultSetting);
		jQuery("#contentDialog").html("");
		jQuery("#mainDialog").dialog("open");
		jQuery(".loadingImg").show();
		jQuery(".ui-dialog-buttonpane").hide(); // hide a 'close' button while loading data
		
		if(defaultSetting.containerID != "") {
			Venda.Ebiz.PopupDialog.loadStaticContent(defaultSetting.containerID);
		} else {
			Venda.Ebiz.PopupDialog.loadDynamicContent(this);
		}
		return false;
	});
});

Venda.Ebiz.PopupDialog.getSettings = function(caller) {
	rulesParsing = jQuery(caller).attr("class");
	rulesRegExp = /\[(.*)\]/;
	getRules = rulesRegExp.exec(rulesParsing);	
	settings = (getRules) ? rulesRegExp.exec(getRules[1]) : null;

	return ((settings) ? settings[1] : null);
};

Venda.Ebiz.PopupDialog.loadDynamicContent = function(caller) {
	jQuery("#contentDialog").load(jQuery(caller).attr("href")+"&layout=noheaders", function() {
		jQuery(".loadingImg").hide();
		jQuery("#mainDialog .demo select").uniform();
		jQuery(".ui-dialog-buttonpane").show(); // show a 'close' button while data loaded
		jQuery("#contentDialog").show();
	});
};

Venda.Ebiz.PopupDialog.loadStaticContent = function(whereID) {
	jQuery("#contentDialog").html(jQuery("#"+whereID).html());
	jQuery("#contentDialog .demo select").uniform();
	jQuery(".loadingImg").hide();
	jQuery(".ui-dialog-buttonpane").show();
	jQuery("#contentDialog").show();
};

Venda.Ebiz.PopupDialog.closeDialog = function() {
	jQuery("#mainDialog").dialog("close");
	jQuery("#mainDialog").dialog("destroy");
};

/**
* Media Code
* Hide noscript comment
* Add listeners to media code form elements
*/
jQuery(document).ready(function(){
	jQuery(".nonjs").css("display","none");
});
/**
* Media Code
* Validate and submit media code using ajax if not on basket for in-page display
* Update minicart figures with ajax too if not on basket
*/
Venda.Ebiz.checkVoucherForm = function(defaulttext, workflow) {
	var str = jQuery("#vcode").val();
	str = jQuery.trim(str);
	if(jQuery("#vcode_submit_shopcart").length > 0){ //if on workflow
		if(str === '' || str === defaulttext) {
			alert(jQuery("#tag-alert").html());
		} else {
			//jQuery("#vcode").val(str.toLowerCase());
			// instead of submit, submit in background to check for errors
			if (document.createElement) {
				var oScript = document.createElement("script");
				oScript.type = "text/javascript";
				if(workflow=='orcf-screen'){
					oScript.src = jQuery("#tag-protocol").html()+"?ex=co_wizr-vouchercodeconfirm&curstep=vouchercode&step=next&mode=process&curlayout=errorsorcf&layout=errorsorcf&vcode="+jQuery("#vcode").val()+"&action=overwrite";
				}else{
					oScript.src = jQuery("#tag-protocol").html()+"?ex=co_wizr-vouchercode&curstep=vouchercode&step=next&mode=process&curlayout=errors&layout=errors&vcode="+jQuery("#vcode").val()+"&action=overwrite";
				}
				document.getElementById("ajax-error").appendChild(oScript);
			}
		}
	}
};

 
Venda.Ebiz.attributesValue ="";
Venda.Ebiz.attributeEMWBIS = function(){
 var attributesValue= document.form.att1.value + document.form.att2.value;
 Venda.Ebiz.attributesValue = product.attributeValues[attributesValue].data["atrsku"];
};

/**
* simple popup
*/
jQuery.fn.createDialog = function(selector, settings, closePopupId){
	var dialogOpts = {autoOpen: false, closeOnEscape:true,resizable: false, modal: true,close: function() {dialogObj.dialog( "destroy" ); dialogObj.remove(); }}
	var H=jQuery(window).height();	
	divObj = jQuery("<div>").attr("id",selector).appendTo("body");
	dialogObj = jQuery(divObj);/* popup object */
	dialogObj.addClass("loadingImg");
		dialogObj.dialog(dialogOpts);
		for( var iSetting in settings){ 
			dialogObj.dialog("option", iSetting, settings[iSetting]);
		}		
		jQuery(".ui-dialog").popupIframe();		
		dialogObj.dialog("open");
		var url = jQuery(this).attr("href");
		/* filter out hash in url */
		if(url.indexOf('#') > 0){ url = url.substr(0,url.indexOf('#'));}
		
		var protocal=document.location.protocol;
		if(url.indexOf("http:")==0 && protocal=="https:") {url=url.replace("http:","https:");}
		dialogObj.load(url+"&layout=noheaders",function(){
			var setHeight = H - dialogObj.height();
			dialogObj.dialog("option","position", setHeight);
			Venda.Ebiz.closeDialog(closePopupId);
			dialogObj.removeClass("loadingImg");
		});
		return false;
};

Venda.Ebiz.closeDialog = function(closePopupId) {
	jQuery(closePopupId).click(function(){
		dialogObj.dialog("close");
		return false;
	});
};

jQuery.fn.submitForm = function(closePopupId){
	var obj = jQuery(this); 
	obj.submit(function() {
		var URL = obj.attr('action'); /* get target*/
		var params = obj.find("input, select, textarea").serialize(); /* get the value from all input type*/
		jQuery.ajax({
			type: "POST", 
			url: URL, 
			dataType: "html", 
            data: params,
			cache: false, /* do not cache*/
			error: function() {
				dialogObj.html('Error!');
			},
			success: function(data) { 
				dialogObj.html(data);
				Venda.Ebiz.closeDialog(closePopupId);
			}
		});
		return false; 
	});
};

Venda.Ebiz.displayProductName = function(productName){
	if(productName){
		jQuery("#emailinstockthankyou #prodname").html(productName);
	}
};

Venda.Ebiz.validateQty = function(id){ 
	var filterNumber = /^\d+$/;
	var qtyVal = jQuery("#"+id).val();
	if(filterNumber.test(qtyVal) && (parseInt(qtyVal) > 0)){
	    jQuery("input[name=qtylist]").val(qtyVal);
		return true;
	}
	else{
		alert(jQuery("#tag-qtymsg").text());
		return false;
	}
};

function DisplayMultiValie(){
	jQuery("tbody tr, thead th.topdetail .pdxt").each(function(){
		var rel=jQuery(this).attr("rel");
		if(typeof(rel)!="undefined" && rel!=""){
			rel=rel.replace(/[^a-zA-Z0-9]+/g,'');
			jQuery(this).attr("rel", rel);
		}
	});
	jQuery("thead th.topdetail").each(function(){
		var index=jQuery(this).index("thead th.topdetail");
		jQuery(this).find(".pdxt").each(function(){
			var rel=jQuery(this).attr("rel");
			var html=jQuery(this).html();
			jQuery("tbody tr[rel="+rel+"]").find("td:eq("+index+") div").html(html)
		});
	});
};

/**
* swapvideo is using for swap video file - used on scat/videoshowcase
* @param (string) videoID is element that contain data
* @param (string) targetTitle is target to set title that get from videoID
* @param (string) targetDesc is target to set description that get from videoID
* @param (string) targetPlayer is target to set viedo player that get from videoID
*/
Venda.Ebiz.swapvideo=function(videoID,targetTitle,targetDesc,targetPlayer,basePath,file){
  var videoURL=basePath+jQuery("#"+videoID+" .video").html();
  var videoDESC=jQuery("#"+videoID+" .detail").html();
  var videoTITLE=jQuery("#"+videoID+" .title").html();
  jQuery("#"+targetDesc).html(videoDESC);
  jQuery("#"+targetTitle).html(videoTITLE);
  jQuery("#"+targetPlayer).html('<object id="player" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" name="player" width="480" height="295"><param name="movie" value="'+ basePath + 'player-licensed.swf" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="flashvars" value="file=' + basePath + file + '&autostart=true" /><embed type="application/x-shockwave-flash" id="'+ videoID + '" name="' + videoTITLE + '" src="' + basePath + 'player-licensed.swf"  width="480"  height="295" allowscriptaccess="always"  allowfullscreen="true" repeat="none" flashvars="file=' + basePath + file + '&autostart=true"/></object>');
};




/* power review for ajax */
var genPwrReviewPath = function(sku){
	var BC=sku;
    var BB = 0;
    var BA;
    for (BA = 0; BA < BC.length; BA++) {
        var A9 = BC.charCodeAt(BA);
        A9 = A9 * Math.abs(255 - A9);
        BB += A9;
    }
    BB = BB % 1023;
    BB = BB + "";
    var BD = 4;
    var A8 = BB.split("");
    for (BA = 0; BA < BD - BB.length; BA++) {
        A8.unshift("0");
    }
    BB = A8.join("");
    BB = BB.substring(0, BD / 2) + ("/" + BB.substring(BD / 2, BD));
    return BB;
};

Venda.Ebiz.pr_review = function(){
	var RatingTxt=["None","Not Good","Needs That Special Something","Average, Ordinary","That's Good Stuff","Perfect. It doesn't get any better"];
	jQuery(".display-pwr").each(function(){
		var $this = jQuery(this);
		var prodsku = jQuery(this).find("span.skuref").html();
		if(prodsku && typeof(prodsku)=="string"){
			var pwrref = 'content/'+genPwrReviewPath(prodsku)+'/contents.js';
			jQuery.getScript('/partners/pwr/'+pwrref, function(){
				var avgStar = 0;
				var totalReview = 0;
				var totalReviewTxt = 'No review';
				try{
					avgStar = POWERREVIEWS.common.gResult[pwrref].locales['en_US']['p'+prodsku]['reviews']['avg'];
					totalReview = POWERREVIEWS.common.gResult[pwrref].locales['en_US']['p'+prodsku]['reviews']['review_count'];
					totalReviewTxt = "("+((totalReview>1)?totalReview+' reviews': totalReview+' review')+")";
				}catch(error){}
				
				roundStar = (Math.round(avgStar*2))/2;
				
				$this.html('<div id="pr-snippet-'+prodsku+'-0" class="pr-snippet"><div class="pr-snippet-wrapper"><div class="pr-snippet-stars"><div class="pr-stars pr-stars-small" style="background-position: 0px '+(roundStar*-36)+'px;" title="'+RatingTxt[Math.floor(avgStar)]+'">&nbsp;</div><span class="pr-snippet-rating-decimal pr-rounded">'+avgStar+'</span></div><p class="pr-snippet-review-count">'+totalReviewTxt+'</p></div></div>');
			});
		}
	});
	if(jQuery("#pr_css").length == 0){
		jQuery("head").append('<link id="pr_css">');
		css = jQuery("head").children(":last");
		css.attr({
			rel:  "stylesheet",
			type: "text/css",
			href: "/partners/pwr/engine/pr_styles_review.css"
		});
	}
};



Venda.namespace("Ebiz.searchResult");
Venda.Ebiz.searchResult.resultSuffix = '&layout=noheaders&template=wz_locayta_result';
Venda.Ebiz.searchResult.refineListSuffix = '&layout=noheaders&template=wz_locayta_refinelist';
Venda.Ebiz.searchResult.init = function(){
	jQuery(document).ready(function(){
		Venda.Ebiz.searchResult.activeNav();
	});
	
	Venda.Ebiz.searchResult.refineListShopClick();
	Venda.Ebiz.searchResult.resultShopClick();
	Venda.Ebiz.searchResult.equalHeight();
	var refineHREF = jQuery("#searchTabNav #supportNav").attr("href");
	Venda.Ebiz.searchResult.loadURL(refineHREF+Venda.Ebiz.searchResult.refineListSuffix,'#refinelistSupported', 0, Venda.Ebiz.searchResult.refineListSupportedClick, true);
	Venda.Ebiz.searchResult.loadURL(refineHREF+Venda.Ebiz.searchResult.resultSuffix,'#supporedtProd', 1, function(){
		jQuery("#searchTabNav #supportNav").addClass("loaded");
		Venda.Ebiz.searchResult.resultCallback();
		if(jQuery("#searchresults .noresulttop").length > 0){
			if(jQuery("#supporedtProd .noresulttop").length == 0){
				jQuery("#searchTabNav #supportNav").click();
			}
			jQuery("#searchresults #noresult").show();
			jQuery("#searchresults #noresult_redirect").hide();
		}
	}, true);
};
Venda.Ebiz.searchResult.equalHeight = function(){
	var classtoset = new Array ('#searchresults .prods .image', '#searchresults .prods ul li .invtdesc2',  '#searchresults .prods ul li .priceDetails',  '#searchresults .prods ul li .price', '#searchresults .prods ul li .details', '#searchresults .prods ul li', '#supporedtProd .prods ul li h2','#supporedtProd .prods .image', '#supporedtProd .prods ul li .invtdesc2',  '#supporedtProd .prods ul li .priceDetails',  '#supporedtProd .prods ul li .price', '#supporedtProd .prods ul li .details', '#supporedtProd .prods ul li');
	Venda.Platform.EqualHeight.init(classtoset);
};

Venda.Ebiz.searchResult.resultCallback = function(){
	Venda.Ebiz.searchResult.resultShopClick();
	Venda.Ebiz.searchResult.resultSupportedClick();
	Venda.Ebiz.searchResult.equalHeight();
	Venda.Widget.MinicartPopup.gatherAdds();
	Venda.Ebiz.searchResult.availScript();
	Venda.Ebiz.checkImg.fix();
};
Venda.Ebiz.searchResult.activeNav = function(){
	jQuery("#searchTabNav a").click(function(e){
		e.preventDefault();
		var currentLink = jQuery(this);
		var index = jQuery(this).index("#searchTabNav a");
		var id = jQuery(this).attr("id");
		var href = jQuery(this).attr("href");
		jQuery("#searchTabNav a").removeClass('now');
		jQuery(this).addClass('now');
		jQuery('#col-one .searchtab').hide().eq(index).show();
		jQuery('#col-two .searchtab').hide().eq(index).show();
		if(id == "supportNav" && !currentLink.is('.loaded')){ /* supported */
			Venda.Ebiz.searchResult.loading();
		}else{
			Venda.Ebiz.searchResult.equalHeight();
		}
		
		if(jQuery("#refinelistShop").is(":visible") && jQuery("#searchresultcompare").length > 0){
			jQuery("#compareProduct").show();
		}else{
			jQuery("#compareProduct").hide();
		}
	});
};
Venda.Ebiz.searchResult.loadingID = 'searchLoading';
Venda.Ebiz.searchResult.loading = function(){
	if(jQuery("#"+Venda.Ebiz.searchResult.loadingID).length > 0){jQuery("#"+Venda.Ebiz.searchResult.loadingID).remove();}
	jQuery("body").append("<div id='"+Venda.Ebiz.searchResult.loadingID+"'></div>");
	var dialogOpts = {autoOpen: false, closeOnEscape:true,resizable: false, modal: true, position: 'center', dialogClass: Venda.Ebiz.searchResult.loadingID,width: 200, height: 120};
	jQuery("#"+Venda.Ebiz.searchResult.loadingID).dialog(dialogOpts).addClass("loadingImg");
	jQuery(".ui-dialog").popupIframe();
	jQuery('.ui-dialog.searchLoading .ui-dialog-titlebar').hide();
	jQuery("#"+Venda.Ebiz.searchResult.loadingID).dialog("open");
	return false;
};
Venda.Ebiz.searchResult.connection = ['', ''];
Venda.Ebiz.searchResult.connectionFlag = [true, true];
Venda.Ebiz.searchResult.loadURL = function(linkurl, target, index, callBack, loadingTrigger){

	if(!Venda.Ebiz.searchResult.connectionFlag[index]){
		Venda.Ebiz.searchResult.connection[index].abort();
	}
	Venda.Ebiz.searchResult.connectionFlag[index] = false;
	
	if(typeof(loadingTrigger)=="undefined"){
		Venda.Ebiz.searchResult.loading();
	}
	Venda.Ebiz.searchResult.connection[index]=jQuery.ajax({
		url:linkurl,
		success: function(data){
			if(index==1){jQuery("#"+Venda.Ebiz.searchResult.loadingID).dialog( "close" );jQuery("#"+Venda.Ebiz.searchResult.loadingID).dialog( "destroy" );jQuery("#"+Venda.Ebiz.searchResult.loadingID).remove();}
			if(data!=""){
				jQuery(target).html(data);
			}
			Venda.Ebiz.searchResult.connectionFlag=true;
			if(typeof(callBack) == "function"){callBack();}
		}
	});
};

Venda.Ebiz.searchResult.refineListSupportedClick=function(){
	jQuery('#refinelistSupported .termtext a, #refinelistSupported .refine-list a').click(function(e){
		e.preventDefault();
		var href = jQuery(this).attr("href");
		Venda.Ebiz.searchResult.loadURL(href+Venda.Ebiz.searchResult.refineListSuffix,'#refinelistSupported', 0, Venda.Ebiz.searchResult.refineListSupportedClick);
		Venda.Ebiz.searchResult.loadURL(href+Venda.Ebiz.searchResult.resultSuffix,'#supporedtProd', 1, Venda.Ebiz.searchResult.resultCallback);
	});
};

Venda.Ebiz.searchResult.resultSupportedClick=function(){
	jQuery('#supporedtProd .pagnNumList a, #supporedtProd .pagnShowViewByPaged a').click(function(e){
		e.preventDefault();
		var href = jQuery(this).attr("href");
		Venda.Ebiz.searchResult.loadURL(href+Venda.Ebiz.searchResult.resultSuffix,'#supporedtProd', 1, Venda.Ebiz.searchResult.resultCallback);
	});
	jQuery('#supporedtProd .sort select[name=sortby], #supporedtProd .pagnPerpage select[name=perpagedpd]').attr("onchange", "");
	jQuery('#supporedtProd .sort select[name=sortby], #supporedtProd .pagnPerpage select[name=perpagedpd]').change(function(e){
		e.preventDefault();
		var href=jQuery(this).val();
		if(href!=""){Venda.Ebiz.searchResult.loadURL(href+Venda.Ebiz.searchResult.resultSuffix,'#supporedtProd', 1, Venda.Ebiz.searchResult.resultCallback);}
	});
};

Venda.Ebiz.searchResult.refineListShopClick=function(){
	jQuery('#refinelistShop .termtext a, #refinelistShop .refine-list a').click(function(e){
		e.preventDefault();
		var href = jQuery(this).attr("href");
		Venda.Ebiz.searchResult.loadURL(href+Venda.Ebiz.searchResult.refineListSuffix,'#refinelistShop', 0, function(){
			Venda.Ebiz.searchResult.refineListShopClick();
			Venda.Widget.VBM.populateProductRecs("vbmsrch","","");
		});
		Venda.Ebiz.searchResult.loadURL(href+Venda.Ebiz.searchResult.resultSuffix,'#searchresults', 1, Venda.Ebiz.searchResult.resultCallback);
	});
};
 
Venda.Ebiz.searchResult.resultShopClick=function(){
	jQuery('#searchresults .pagnNumList a,#searchresults .pagnShowViewByPaged a').click(function(e){
		e.preventDefault();
		var href = jQuery(this).attr("href");
		Venda.Ebiz.searchResult.loadURL(href+Venda.Ebiz.searchResult.resultSuffix,'#searchresults', 1, Venda.Ebiz.searchResult.resultCallback);
	});
	jQuery('#searchresults .sort select[name=sortby], #searchresults .pagnPerpage select[name=perpagedpd]').attr("onchange", "");
	jQuery('#searchresults .sort select[name=sortby], #searchresults .pagnPerpage select[name=perpagedpd]').change(function(e){
		e.preventDefault();
		var href=jQuery(this).val();
		if(href!=""){Venda.Ebiz.searchResult.loadURL(href+Venda.Ebiz.searchResult.resultSuffix,'#searchresults', 1, Venda.Ebiz.searchResult.resultCallback);}
	});
};

Venda.Ebiz.searchResult.toggle = function(toggleName, sender){
	var linktext = jQuery(sender).text();
	var viewall = document.getElementById("tag-refineviewall").innerHTML;
	var viewless = document.getElementById("tag-refineviewless").innerHTML;
	jQuery(sender).text((linktext==viewall)?viewless:viewall);
	jQuery(sender).parents(".refinelist").find('.'+toggleName).toggle();
};

Venda.Ebiz.searchResult.availScript = function(){
	termToProduct();
	Venda.Ebiz.pr_review();
	
	if(jQuery("#refinelistShop").is(":visible")){
		if(jQuery("#refinelistShop #searchresultcompare").length > 0){
			var searchresultcompare = jQuery("#refinelistShop #searchresultcompare").html();
			jQuery("#searchresults .prods ul li .compbutton").css("display","block");
			jQuery("#compareProduct").show();
		}else{
			try{
				Venda.Widget.Compare.deleteAll();
			}catch(err){
				/* catch any error */
			};
		}
	}
	jQuery(".searchtab select").parent().not(".selector").find("select").uniform();
};


jQuery(document).ready(function() {
	/**
	* Display Social book marks box when mouse hover
	*/
	jQuery("#socialBookMarks").hover(
	function() {
		jQuery("#SBcontent").css({"left":"-1px"});
		},
		function() {
		jQuery("#SBcontent").css({"left":"-9999px"});
		}
	);
	/**
	* Popup Download Link Page
	*/	
	jQuery(".downloadLink").click(function(){
		jQuery(this).createDialog('download', {'dialogClass':'download','width':'540px'}, '');
		return false;
	});
});

Venda.namespace("Ebiz.video");
Venda.Ebiz.video=function(){};
Venda.Ebiz.video.init=function(config){	
	this.catwalkwrapper=config[0];
	this.catwalk_link=config[1];
	this.productdetail_catwalk=config[2];
	this.productdetail_image=config[3];
	this.catwalklabel=jQuery("#"+config[4]).html();
	this.imglabel=jQuery("#"+config[5]).html();
	jQuery("#"+Venda.Ebiz.video.catwalk_link).bind("click",Venda.Ebiz.video.show);
};
Venda.Ebiz.video.show=function(){
	jQuery(".invtmedia .overlay,#"+Venda.Ebiz.video.productdetail_image).hide();
	var videoURL = jQuery("#"+Venda.Ebiz.video.catwalk_link).attr("href");
	jQuery("#"+Venda.Ebiz.video.catwalkwrapper).show();
	jQuery("#productdetail-viewlarge").hide();
	jQuery("#"+Venda.Ebiz.video.catwalk_link).unbind("click",Venda.Ebiz.video.show);
	jQuery("#"+Venda.Ebiz.video.catwalk_link).bind("click",Venda.Ebiz.video.hide);
	jQuery("#"+Venda.Ebiz.video.catwalk_link).html(Venda.Ebiz.video.imglabel);
	jQuery("#"+Venda.Ebiz.video.catwalkwrapper).load(videoURL, function(){
		jQuery("#productdetail-altviewVDO a:first").trigger("click");
	});
	return false;
};
Venda.Ebiz.video.hide=function(){
	jQuery("#"+Venda.Ebiz.video.catwalkwrapper).hide();
	jQuery("#productdetail-viewlarge").show();
	jQuery(".invtmedia .overlay,#"+Venda.Ebiz.video.productdetail_image).show();
	jQuery("#"+Venda.Ebiz.video.catwalkwrapper).html('<div id="'+Venda.Ebiz.video.productdetail_catwalk+'"></div>');
	jQuery("#"+Venda.Ebiz.video.catwalk_link).unbind("click",Venda.Ebiz.video.hide);
	jQuery("#"+Venda.Ebiz.video.catwalk_link).bind("click",Venda.Ebiz.video.show);
	jQuery("#"+Venda.Ebiz.video.catwalk_link).html(Venda.Ebiz.video.catwalklabel);
	return false;
};

Venda.Ebiz.video.swapYoutubeVDO = function(targetPlayer, vlink) {
jQuery("#"+targetPlayer).html('<object width="395" height="300"><param name="movie" value="'+vlink+'&amp;hl=en_US&amp;fs=1&amp;autoplay=0"></param><param name="wmode" value="transparent"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="'+vlink+'&amp;hl=en_US&amp;fs=1&amp;autoplay=0" wmode="transparent" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="395" height="300"></embed></object>');
};

var AvailEqualHeight = function(){
	if(Venda.Platform.EqualHeight){
	var classtoset = new Array ('li .toggle_name');
	Venda.Platform.EqualHeight.init(classtoset);
	}
};

// Gift certificate - input on order summary
jQuery(document).ready(function() {
	jQuery("#giftcode").keypress(function(event) {
		if (event.which == "13") {
			jQuery("#applyCode").trigger("click");
			return false;
		}
	});
});

Venda.Ebiz.validateGiftcode = function(formName, msg) {
	if (document.forms[formName].giftcode.value == ""){
		alert(msg);
		document.forms[formName].giftcode.focus();
		return false;
	}
	document.forms[formName].step.value = "confirm";
	document.forms[formName].param1.value = "show";
	document.forms[formName].param2.value = "giftcert";
	document.forms[formName].submit();
};

 /**
 * formValidate - is name space for validate user address fields, normally use in contact address, delivery address page
 */
Venda.namespace("Ebiz.formValidate");

Venda.Ebiz.formValidate=function(){};


 /**
 * chkField - check required field
 * @param {string} form name
 * @param {string} field name
 * @param {string} error message when blank
 */
Venda.Ebiz.formValidate.chkField = function(form, elm, errMsg) {	
	var curElm = document.forms[form].elements[elm];	
	if (curElm.value != '' && curElm.value.length != 0) {
		return true; 
	} else {
		if (arguments[2] != undefined) {
			alert(errMsg);
			curElm.focus();
		}
		return false;
	}
};

 /**
 * isNum - check field value is number or not
 * @param {string} form name
 * @param {string} field name
 * @param {string} error message when value isn't number
 */
Venda.Ebiz.formValidate.isNum = function(form, elm, errMsg) {
	var numOnly =/^\d+$/;
	var curElm = document.forms[form].elements[elm];
	var strpdField = curElm.value.replace(/\s+/g,'');
	if (numOnly.test(strpdField)) {  
		return true;
	} else {
		if (arguments[2] != undefined) {
			alert(errMsg);
			curElm.focus();
		}
		return false;
	}
};

/**
 * chkDropdown - check dropdown is selected or not
 * @param {string} form name
 * @param {string} field name
 * @param {string} error message when not selected
 */
Venda.Ebiz.formValidate.chkDropdown = function(form, elm, errMsg) {
	var objDropdown = document.forms[form].elements[elm];
	var objSelectValue = objDropdown.options[objDropdown.selectedIndex].value; 
	if (objSelectValue != "") {
		return true;
	} else {
		if (arguments[2] != undefined) {
			alert(errMsg);
			objDropdown.focus();
		}
		return false;
	}
}

/**
 * chkFieldFormat - check field with customized format
 * @param {string} form name
 * @param {string} field name
 * @param {string} error message when not selected
 * @param {regEx} regular expression
 */
Venda.Ebiz.formValidate.chkFieldFormat = function(form, elm, errMsg, regEx){
	var curElm = document.forms[form].elements[elm];	
	if(regEx.test(curElm.value)){
		return true; 
	}else{
		alert(errMsg);
		curElm.focus();
		return false;
	}
}

 /**
 * checkImg - check image on error (missing image .. or path incorrect from yourZoom). check only image has class name key-x-small, key-small, key-medium, key-medium2, key-large and key-x-large
 * if found any error on the image, then replace with on image that match to key.
 */
Venda.namespace("Ebiz.checkImg");
Venda.Ebiz.checkImg.path = '/content/ebiz/igo/resources/images/no_image_';
Venda.Ebiz.checkImg.fix = function(){
	var imgSelector = "img.key-xsmall, img.key-small, img.key-medium, img.key-medium2, img.key-large, img.key-x-large, img.key-vdo";
	jQuery(imgSelector).each(function(){
		if(jQuery(this).is("img")){
			var img = new Image();
			var sender = jQuery(this);
			var classname = sender.attr("class");
			var src=sender.attr("src");
			var keyImg=classname.match(/key-([a-zA-Z0-9]+)/);
			keyImg = keyImg[1];
			jQuery(img).load(function(){
				/* success do nothing */
				if(sender.is(".hide")){sender.show();}
				sender.removeClass("key-xsmall key-small key-medium key-medium2 key-large key-x-large key-vdo");
			}).error(function(){
				if(!sender.is(".hide")){
					sender.attr("src", Venda.Ebiz.checkImg.path+keyImg+".gif").show();
				}
				sender.addClass('no-img')
				sender.removeClass("key-xsmall key-small key-medium key-medium2 key-large key-x-large key-vdo");
			}).attr('src', src);
		}
	});
};

Venda.namespace("Ebiz.altview");
Venda.Ebiz.altview.message = {
	alternateViewAltText: '',
	alternateViewTitleText: '',
	alternateViewHeaderText: '',
	closeTextLink: '',
	closePanelTitle: ''
};
Venda.Ebiz.altview.images = {};
Venda.Ebiz.altview.create = function(yourzoom){
	var output= '';
	for(var num=0;num<this.images['xsmall'].length;num++){
		if(this.images['xsmall']!=""){
			output+='<div><a href="'+this.images['large'][num]+'"><img src="'+this.images['xsmall'][num]+'" class="key-xsmall hide"></a></div>';
		}
	}
	jQuery("#productdetail-altview").html(output);
	jQuery("#productdetail-altview a").addClass("selected");
	jQuery("#productdetail-altview a").click(function(e){
		e.preventDefault();
		var src = this.href;
		var img = new Image();
		jQuery("#productdetail-image a").html('<img src="'+src+'" class="key-large" alt="'+jQuery("#tag-invtname").html()+'">');
		Venda.Ebiz.checkImg.fix();
	});
	
	if(typeof(yourzoom)=="undefined" || yourzoom!=1){
		/* hide and remove Click function on enlarge link and image */
		jQuery("#productdetail-viewlarge").hide();
		jQuery("#productdetail-image a, #enlarge_link").click(function(e){e.preventDefault();});
		
		var src = jQuery("#productdetail-image a").find('img').attr("src");
		var largeImg = new Image();
		jQuery(largeImg).load(function(){
			jQuery("#productdetail-viewlarge").show();
			Venda.Ebiz.altview.enlargeLink();
		}).error(function(){
			/* remove link from main image */
			jQuery("#productdetail-image a img").unwrap();
			jQuery("#productdetail-altview").hide();
		}).attr("src", src);
	}else{
		jQuery('#your_zoom_img, #your_zoom_link').bind('click', function(e){
			e.preventDefault();
			if(typeof(yzOpenWin) == "function"){yzOpenWin(this.href, 820, 575);}
		});
		var src = jQuery("#productdetail-image a").find('img').attr("src");
		var largeImg = new Image();
		jQuery(largeImg).load(function(){
			jQuery("#your_zoom_link").show();
			jQuery('#your_zoom_img, #your_zoom_link').bind('click', function(e){
				e.preventDefault();
				if(typeof(yzOpenWin) == "function"){yzOpenWin(this.href, 820, 575);}
			});
		}).error(function(){
			/* remove link from main image */
			jQuery("#productdetail-image a img").unwrap();
			jQuery("#productdetail-altview").hide();
		}).attr("src", src);
	}
};
Venda.Ebiz.altview.enlargeLink = function(){
	jQuery("#productdetail-image a, #enlarge_link").click(function(e){
		e.preventDefault();
		var img_url = this.href;
		var selector = "viewlarge_popup";
		var alternateViewList="";
		var invt_name = jQuery("#tag-invtname").html();
		if(!jQuery("#productdetail-image a").find('img').is('.no-img')){
			var dialogOpts = {width: 520, dialogClass: 'viewlarge', position: "center", autoOpen: false, closeOnEscape:true, resizable: false, modal: true, close: function() {dialogObj.dialog( "destroy" ); dialogObj.remove();}};
			var H=jQuery(window).height();	
			divObj = jQuery('<div id="'+selector+'"></div>').attr("id", selector).appendTo("body");
			dialogObj = jQuery(divObj);/* popup object */
			dialogObj.addClass("loadingImg").dialog(dialogOpts);
			jQuery(".ui-dialog").popupIframe();
			dialogObj.dialog("open");
			
			jQuery("#productdetail-altview a img:visible").each(function(){
				alternateViewList+='<a href="'+jQuery(this).parent().attr("href")+'" title="'+invt_name+" - "+Venda.Ebiz.altview.message.alternateViewTitleText+'"><img src="'+this.src+'" alt="'+invt_name+" - "+Venda.Ebiz.altview.message.alternateViewAltText+'"></a>';
			});
			dialogObj.html('<div class="popupContents"><h1>'+invt_name+'</h1>'+
					'<div id="mainImage"></div>'+
					'<div id="alternateViewList"><p class="altviewHeader">'+Venda.Ebiz.altview.message.alternateViewHeaderText+'</p>'+alternateViewList+'</div>'+
				'<div class="clear-all"></div></div>');
			var setHeight = H - dialogObj.height();
			jQuery("#mainImage").delegate("a", "click",function(e){
				e.preventDefault();
				dialogObj.dialog("close");
			});
			if(jQuery("#alternateViewList a").length < 2){
				jQuery("#alternateViewList").hide();
			}
			jQuery("#alternateViewList a").click(Venda.Ebiz.altview.thumbClick);
			jQuery("#alternateViewList a:first").click();
		}
	});
};
Venda.Ebiz.altview.thumbClick = function(e){
	e.preventDefault();
 /* change img */
	var img = new Image();
	var sender = jQuery(this);
	var img_url=sender.attr("href");
	jQuery(img).load(function(){
		/* success do nothing */
		jQuery("#mainImage").html('<a href="'+img_url+'" title="'+Venda.Ebiz.altview.message.closePanelTitle+'"><img src="'+img_url+'"></a>');
		dialogObj.dialog("option","position", ["center", "center"]).removeClass("loadingImg");
	}).error(function(){
		keyImg = "large";
		jQuery("#mainImage").html('<a href="#" title="'+Venda.Ebiz.altview.message.closePanelTitle+'"><img src="'+Venda.Ebiz.checkImg.path+keyImg+".gif"+'"></a>');
		sender.addClass('no-img');
		dialogObj.dialog("option","position", ["center", "center"]).removeClass("loadingImg");
	}).attr('src', img_url);
};

/**
 display floating div
**/
Venda.Ebiz.floatingDiv = function(){
	var cfg = {top: 225, left: 0, zIndex: 3, delay: 0};
	$this = jQuery(".floatwrapper");
	$this.appendTo("body");
	$this.css({"position": 'fixed', "z-index": cfg.zIndex, "left": cfg.left, "top": cfg.top});
	jQuery(window).scroll(function(){
		//var top = jQuery(this).scrollTop();
		$this.animate({"top": cfg.top}, {duration: cfg.delay, queue: false});
	});
};


/* Add Class */
 jQuery(document).ready(function(){
	jQuery("#lftnav_basket .helpinfo ul li:last").addClass("last");
	jQuery("#yourbasket .ordertable .wizrtable tbody tr:last").addClass("last");
	jQuery("#yourbasket .wizrtable tbody tr:first").addClass("first");
	jQuery("#checkout .checkoutR .checkoutMinicart #minicart_products li:first").addClass("first");
	jQuery("#ordersummary table.wizrtable tbody tr:last").addClass("last");
	jQuery(".ohSumDetail table.wizrtable tbody tr:last").addClass("last");
	jQuery("#basketfeatmodule #featProds ul li:first").addClass("first");
	Venda.Ebiz.checkImg.fix();
  
	if (jQuery(".home_newsbox").length >= 1) {
		jQuery(".home_newsbox").scrolling({
			listClassName: ".items",
			autoSlideTime: 3000,
			slideSpeed: 300,
			autoSlide: true
		});
	}
	Venda.Ebiz.floatingDiv();
	
	//Blur focus from textbox when mouseover top navgiation
	jQuery(".topnavmenu #mm_ul").hover(function() {
		jQuery("input:focus").blur();
	});
});

/**
 * Confirm Add tip widget on Productlist
 * @param {string} Sku
 * @param {string} URL
 */
Venda.Ebiz.checkAddTipProductlist = function(sku,url){
	var confirmmsg = "You are entitled to one free tip. Click OK to buy just the Adapter or Cancel to select your free Tip ?";
	if(confirm(confirmmsg)){
		return true;
	}
	else
	{
		window.location.href= url;
		return false;
	}

};

/**
 * Clear promotion on Unload window / Log out
 * @param (string) destT
*/

Venda.Ebiz.clearPromo = function(destT){
	var destinationPath = destT;
	if(destinationPath){
		ajaxFunction('/bin/venda?ex=co_wizr-shopcart&curstep=handle_vouchercode&step=handle_vouchercode&mode=process&action=delete','currLang',null,function(){window.location.href = destinationPath;});
	}
	else{
		ajaxFunction('/bin/venda?ex=co_wizr-shopcart&curstep=handle_vouchercode&step=handle_vouchercode&mode=process&action=delete','currLang',null,function(){/* nothing */});
	}
};

/* Scroll to Top Widget */
Venda.Ebiz.scrolltop = function() {
    var top = "";
	var top = jQuery(".tipspopup").css("top");
	if(top == undefined){ top = jQuery(".addmydevices").css("top");}
	if(top == undefined){ top = 0;}
	top = top.replace("px","");
	scroll(0,top);
};
