/* Common Javascript functions for use throughout TungStenShopping Shopping Cart */

// Fetch the value of a cookie
function get_cookie(name) {
	name = name += "=";
	var cookie_start = document.cookie.indexOf(name);
	if(cookie_start > -1) {
		cookie_start = cookie_start+name.length;
		cookie_end = document.cookie.indexOf(';', cookie_start);
		if(cookie_end == -1) {
			cookie_end = document.cookie.length;
		}
		return unescape(document.cookie.substring(cookie_start, cookie_end));
	}
}

// Set a cookie
function set_cookie(name, value, expires)
{
	if(!expires) {
		expires = "; expires=Wed, 1 Jan 2020 00:00:00 GMT;"
	} else {
		expire = new Date();
		expire.setTime(expire.getTime()+(expires*1000));
		expires = "; expires="+expire.toGMTString();
	}
	document.cookie = name+"="+escape(value)+expires;
}

/* Javascript functions for the products page */
var num_products_to_compare = 0;
var product_option_value = "";

function showProductImage(filename, product_id) {
	var l = (screen.availWidth/2)-350;
	var t = (screen.availHeight/2)-300;
	var variationAdd = '';
	if($('body').attr('currentVariation') != '' && typeof($('body').attr('currentVariation')) != "undefined") {
		variationAdd = '&variation_id='+$('body').attr('currentVariation');
	}
	window.open(filename + "?product_id="+product_id+variationAdd, "imagePop", "toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=700,height=600,top="+t+",left="+l);
}

function getEvent() //同时兼容ie和ff的写法 
    {  
        if(document.all)  return window.event;    
        func=getEvent.caller;        
        while(func!=null){  
            var arg0=func.arguments[0]; 
            if(arg0) 
            { 
              if((arg0.constructor==Event || arg0.constructor ==MouseEvent) || (typeof(arg0)=="object" && arg0.preventDefault && arg0.stopPropagation)) 
              {  
              return arg0; 
              } 
            } 
            func=func.caller; 
        } 
        return null; 
    } 

function ReplaceString(string){
   var r, re;                    // 声明变量。
   re = /_thumb/g;             // 创建正则表达式模式。
   r = string.replace(re, "");    // 用 "" 替换 "_thumb"。
   return(r);                   // 返回替换后的字符串。
}


function showPic(object){
	picurl = object.src;
	istrue = picurl.indexOf('=');
	if(istrue>0){
    bigpic = picurl.split('=');
	picurl = bigpic[3];
	}
	isthum = picurl.indexOf('_thumb');
	if(isthum>0) {
    picurl = ReplaceString(picurl);
	}
	var obj = document.getElementById("bigimage");
	var style;
        if (navigator.appName=='Microsoft Internet Explorer') { 
         style = "style='position:absolute;margin-top:3px;margin-left:-140px;z-index:1000;border:5px solid #CCCCCC;background:#FFFFFF'"; 
        }else if (navigator.appName=='Netscape') { 
         style = "style='position:absolute;z-index:1000;border:5px solid #CCCCCC;background:#FFFFFF'";
        } 
	obj.innerHTML = "<div " + style + "><img style='padding:3px;' src=\"" + picurl + "\"></div>";
	obj.style.display = "block";
}

function hiddenPic(){
	document.getElementById("bigimage").innerHTML = "";
	document.getElementById("bigimage").style.display = "none";
}

function changBigPic(object) {
var thumobj = document.getElementById('ThumbImage');
picurl = object.src;
thumurl = picurl.split('=');
thumobj.src = '/picresize.php?w=200&h=200&url=' + thumurl[3];
}

function CheckProductConfigurableFields(form)
{
	var requiredFields = $('.FieldRequired');
	var valid = true;
	requiredFields.each(function() {
		var namePart = this.name.replace(/^.*\[/, '');
		var fieldId = namePart.replace(/\].*$/, '');
		
		if(this.type=='checkbox' ) {
			if(!this.checked) {
				valid = false;
				alert(lang.EnterRequiredField);
				this.focus();
				this.select();
				return false;
			}
		} else if(this.value == '') {
			if(this.type != 'file' || (this.type == 'file' && document.getElementById('CurrentProductFile_'+fieldId).value == '')) {
				valid = false;
				alert(lang.EnterRequiredField);
				this.focus();
				this.select();
				return false;
			}
		}
	});

	var fileFields = $(form).find('input[type=file]');
	fileFields.each(function() {
		if(this.value != '') {
			var namePart = this.name.replace(/^.*\[/, '');
			var fieldId = namePart.replace(/\].*$/, '');
			var fileTypes = document.getElementById('ProductFileType_'+fieldId).value;

			fileTypes = ','+fileTypes.replace(' ', '').toLowerCase()+','
			var ext = this.value.replace(/^.*\./, '').toLowerCase();

			if(fileTypes.indexOf(','+ext+',') == -1) {
				alert(lang.InvalidFileTypeJS);
				this.focus();
				this.select();
				valid = false;
			}

		}
	});

	return valid;
}

function check_add_to_cart(form, required) {
	var valid = true;
	var qtyInputs = $(form).find('input.qtyInput');
	qtyInputs.each(function() {
		if(isNaN($(this).val()) || $(this).val() <= 0) {
			alert(lang.InvalidQuantity);
			this.focus();
			this.select();
			valid = false;
			return false;
		}
	});
	if(valid == false) {
		return false;
	}

	if(!CheckProductConfigurableFields(form)) {
		return false;
	}

	if(required && !$(form).find('.CartVariationId').val()) {
		alert(lang.OptionMessage);
		var select = $(form).find('select').get(0);
		if(select) {
			select.focus();
		}
		var radio = $(form).find('input[type=radio]').get(0);
		if(radio) {
			radio.focus();
		}
		return false;
	}

	return true;
}

function compareProducts(compare_path) {
	var pids = "";
	
	if($('form').find('input[name=compare_product_ids][checked]').size() >= 2) {
		var cpids = document.getElementsByName('compare_product_ids');

		for(i = 0; i < cpids.length; i++) {
			if(cpids[i].checked)
				pids = pids + cpids[i].value + "/";
		}

		pids = pids.replace(/\/$/, "");
		document.location.href = compare_path + pids;
		return false;
	}
	else {
		alert(lang.CompareSelectMessage);
		return false;
	}
}

function product_comparison_box_changed(state) {
	// Increment num_products_to_compare - needs to be > 0 to submit the product comparison form
	
	
	if(state)
		num_products_to_compare++;
	else
		if (num_products_to_compare != 0)
			num_products_to_compare--;
}

function remove_product_from_comparison(id) {
	if(num_compare_items > 2) {
		for(i = 1; i < 11; i++) {
			document.getElementById("compare_"+i+"_"+id).style.display = "none";
		}

		num_compare_items--;
	}
	else {
		alert(lang.CompareTwoProducts);
	}
}

function show_product_review_form() {
	document.getElementById("rating_box").style.display = "";
	document.location.href = "#write_review";
}

function jump_to_product_reviews() {
	document.location.href = "#reviews";
}

function g(id) {
	return document.getElementById(id);
}

function check_product_review_form() {
	var revrating = g("revrating");
	var revtitle = g("revtitle");
	var revtext = g("revtext");
	var revfromname = g("revfromname");
	var captcha = g("captcha");

	if(revrating.selectedIndex == 0) {
		alert(lang.ReviewNoRating);
		revrating.focus();
		return false;
	}

	if(revtitle.value == "") {
		alert(lang.ReviewNoTitle);
		revtitle.focus();
		return false;
	}

	if(revtext.value == "") {
		alert(lang.ReviewNoText);
		revtext.focus();
		return false;
	}

	if(captcha.value == "" && HideReviewCaptcha != "none") {
		alert(lang.ReviewNoCaptcha);
		captcha.focus();
		return false;
	}

	return true;
}

function check_small_search_form() {
	var search_query = g("search_query");

	if(search_query.value == "") {
		//alert(lang.EmptySmallSearch);
		alert('Please type in your key words.');
		search_query.focus();
		return false;
	}

	return true;
}

function setCurrency(currencyId)
{
	var gotoURL = location.href;

	if (location.search !== '')
	{
		if (gotoURL.search(/[&|\?]setCurrencyId=[0-9]+/) > -1)
			gotoURL = gotoURL.replace(/([&|\?]setCurrencyId=)[0-9]+/, '$1' + currencyId);
		else
			gotoURL = gotoURL + '&setCurrencyId=' + currencyId;
	}
	else
		gotoURL = gotoURL + '?setCurrencyId=' + currencyId;

	location.href = gotoURL;
}


// Dummy sel_panel function for when design mode isn't enabled
function sel_panel(id) {}

function inline_add_to_cart(filename, product_id, quantity, returnTo) {
	if(typeof(quantity) == 'undefined') {
		var quantity = '1';
	}
	var html = '<form action="' + filename + '/cart.php" method="post" id="inlineCartAdd">';
	if(typeof(returnTo) != 'undefined' && returnTo == true) {
		var returnLocation = window.location;
		html += '<input type="hidden" name="returnUrl" value="'+escape(returnLocation)+'" />';		
	}
	html += '<input type="hidden" name="action" value="add" />';
	html += '<input type="hidden" name="qty" value="'+quantity+'" />';
	html += '<input type="hidden" name="product_id" value="'+product_id+'" />';
	html += '<\/form>';
   $('body').append(html);
   $('#inlineCartAdd').submit();
}


// Dummy JS object to hold language strings.
var lang = {
};

// IE 6 doesn't support the :hover selector on elements other than links, so
// we use jQuery to work some magic to get our hover styles applied.
if(document.all) {
	var isIE7 = /*@cc_on@if(@_jscript_version>=5.7)!@end@*/false;
	if(isIE7 == false) {
		$(document).ready(function() {
			$('.ProductList li').hover(function() {
				$(this).addClass('Over');
			},
			function() {
				$(this).removeClass('Over');
			});
			$('.ComparisonTable tr').hover(function() {
				$(this).addClass('Over');
			},
			function() {
				$(this).removeClass('Over');
			});
		});
	}
	$('.ProductList li:last-child').addClass('LastChild');
}

$(document).ready(function() {
	$('.InitialFocus').focus();
	$('table.Stylize tr:first-child').addClass('First');
	$('table.Stylize tr:last-child').addClass('Last');
	$('table.Stylize tr td:odd').addClass('Odd');
	$('table.Stylize tr td:even').addClass('Even');
	$('table.Stylize tr:even').addClass('Odd');
	$('table.Stylize tr:even').addClass('Even');
	
	$('.TabContainer .TabNav li').click(function() {
		$(this).parent('.TabNav').find('li').removeClass('Active');
		$(this).parents('.TabContainer').find('.TabContent').hide();
		$(this).addClass('Active');
		$(this).parents('.TabContainer').find('#TabContent'+this.id).show();
		$(this).find('a').blur();
		return false;
	});
	
});

//控制菜单显示

function updatestatus(id) {
	var id=id+'_1';
	var obj = document.getElementById(id);

	if(obj){
		if(obj.style.display=='none') {
			obj.style.display='block';  
		} else {
			obj.style.display='none';  
		}
	}
}

//轮播程序
function banner() {
<!--
                var picarry = {};
                var lnkarry = {};
                var ttlarry = {};
                var img = {};
                var link = {};
                var text = {};
                
                var pics="";
                var links="";
                var texts="";
 
                  function FixCode(str){
                    return str.replace("'","=");
                  }
                  var t=document.getElementById("pictable");
                  var rl=t.rows.length;
                  var baseu=  document.URL.replace(/(http.*\/)(.*)/, "$1"); 
                  if(baseu.indexOf("/servlet/")>=0)
                  baseu = baseu.replace("/servlet/","/");

                  var txt="";
                  
                  for(var i=0;i<rl;i++){
                    try{
                        img[i]=picarry[i]=t.rows[i].cells[0].childNodes[0].src;
                        link[i]=lnkarry[i]=t.rows[i].cells[2].innerHTML;
                        text[i]=ttlarry[i]=FixCode(t.rows[i].cells[1].innerHTML);
                        
                        pics+=img[i];
                        links+=link[i];
                        texts+=text[i];
                        
                        if(i<(rl-1))
                        {
                          pics+="|";
                          links+="|";
                          texts+="|";
                        }
                    }catch(e){
        
                    }
                }    

 var focus_width=609
 var focus_height=280
 var text_height=20
 var swf_height = focus_height+text_height
  
 document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="'+ focus_width +'" height="'+ swf_height +'">');
 document.write('<param name="allowScriptAccess" value="sameDomain"><param name="movie" value="/flash/focus.swf"><param name="quality" value="high"><param name="bgcolor" value="#fff">');
 document.write('<param name="menu" value="false"><param name=wmode value="transparent">');
 document.write('<param name="FlashVars" value="pics='+pics+'&links='+links+'&texts='+texts+'&borderwidth='+focus_width+'&borderheight='+focus_height+'&textheight='+text_height+'">');
  document.write('<embed src="/flash/focus.swf" quality="high" FlashVars="pics='+pics+'&links='+links+'&texts='+texts+'&borderwidth='+focus_width+'&borderheight='+focus_height+'&textheight='+text_height+'" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" wmode="transparent" type="application/x-shockwave-flash" width="'+ focus_width +'" height="'+ swf_height +'"><\/embed>');
 document.write('<\/object>');
}

/*标签切换开始*/
function c(id){
	var i;
	for(i=1;i<=3;i++){
      if(i==id) {
	  document.getElementById("laberprod").style.backgroundImage = 'url(/templates/Electronics/images/newpro_'+id+'.gif)';
      document.getElementById("block_"+i).style.display="block";
      document.getElementById("listmore_"+i).style.display="block";
	  } else {
      document.getElementById("block_"+i).style.display="none";
	  document.getElementById("listmore_"+i).style.display="none";
	  }
	}
}

/*标签切换结束*/

function checkform() {
var name = document.getElementById("gname");
var country = document.getElementById("gcountry");
var email= document.getElementById("gemail");
var content = document.getElementById("gcontent");
var obj = document.getElementById("msg");
var reEmail = /^([A-Za-z0-9])(\w)+@(\w)+(\.)(com|com\.cn|net|cn|net\.cn|org|biz|info|gov|gov\.cn|edu|edu\.cn)/;
if(name.value=='' || name.value.length>60) {
obj.innerHTML = "Name of length must between 1 to 60 words";
return false;
}
if(country.value=='') {
obj.innerHTML = "Please select country";
return false;
}
if(email.value=='' || email.value.length>60) {
obj.innerHTML = "E-mail of length must between 1 to 60 words";
return false;
} else if(!email.value.match(reEmail)) {
obj.innerHTML = "E-mail is invalid";
}
if(content.value=='' || email.value.length>500) {
obj.innerHTML = "Content of length must between 1 to 60 words";
return false;
}
return true;
}

function gotoGoogle(url) {
window.location.href=url;
}

var state = 0;
var chishu = 1;
var thetimer;
function show(id) {

var obj = document.getElementById("chatinfo_"+id);
	if(obj.style.display=="block") {
    obj.style.display="none";
    /*thetimer = setTimeout("change()", 2000);*/
	} else {
    obj.style.display="block";
    clearTimeout(thetimer);
    state = 1;
    chishu = id;
	}
	

}

function hidden(id) {
var obj = document.getElementById("chatinfo_"+id);
    obj.style.display="none";
	<!--thetimer = setTimeout("change()", 2000);-->
}

function change() {

for(i=1;i<=2;i++) {
var bj = document.getElementById("csman_"+i);
var bjc = document.getElementById("chatinfo_"+i);
bj.style.display = "none";
bjc.style.display = "none";
}
id = sss();
var bjn = document.getElementById("csman_"+id);
bjn.style.display='block';
/*thetimer = setTimeout("change()", 2000);*/
}

var j=1;
function sss() {
if(state) {
state=0;
j = chishu;
}

if(j<2)
{
j++;
}
else 
{
j=1;
}
return j;
}

function connectsfnchat() {
var lpButtonCTTUrl = 'http://kf.eshopwalk.com/kf.php?mod=client&mq=100017';
window.open(lpButtonCTTUrl,'chat100010','width=700px,height=472px,resizable=yes');
}

function showbookmark(id) {
var obj = document.getElementById(id);
    if(obj.style.display=='block'){
		obj.style.display='none';
	} else {
        obj.style.display='block';
	}

}

function setvalue(data) {
var obj = document.getElementById("product_color");
obj.value = data;
}

function displayitems(id) {
var obj = document.getElementById(id);
if(obj.style.display=="none") {
obj.style.display = "block";
} else {
obj.style.display = "none";
}

}

/*缩略图翻页*/
function viewpage(direc) {
var currentpage = document.getElementById("currentPage");
var totalpage = document.getElementById("totalPage").value;
for(i=0;i<totalpage;i++) {
var obj = document.getElementById("page"+i);
obj.style.display = "none";
}
var next = currentpage.value;

next = currentpage.value;
if(direc=='next') {
next++;
if(next>=totalpage) {
next = 0;	
}
} else {
next--;
if(next<=-1) {
next = (totalpage-1);	
}	
	
}
currentpage.value=next;
document.getElementById("page"+next).style.display="block";
}
/*产品页弹出隐藏层*/
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

/*展示产品页大图*/
function show_bigPic(id) {
var obj = document.getElementById(id);
picurl = obj.src;
thumurl = picurl.split('=');
window.open ('/'+thumurl[3], 'newwindow', 'height=600, width=600, top=200, left=200, toolbar=no, menubar=no, scrollbars=no, resizable=yes,location=no, status=no');
}

function checkform() {
var name = document.getElementById("gname");
var country = document.getElementById("gcountry");
var email= document.getElementById("gemail");
var content = document.getElementById("gcontent");
var obj = document.getElementById("msg");
var reEmail = /^([A-Za-z0-9])(\w)+@(\w)+(\.)(com|com\.cn|net|cn|net\.cn|org|biz|info|gov|gov\.cn|edu|edu\.cn)/;
if(name.value=='' || name.value.length>60) {
obj.innerHTML = "Name of length must between 1 to 60 words";
return false;
}
if(country.value=='') {
obj.innerHTML = "Please select country";
return false;
}
if(email.value=='' || email.value.length>60) {
obj.innerHTML = "E-mail of length must between 1 to 60 words";
return false;
} else if(!email.value.match(reEmail)) {
obj.innerHTML = "E-mail is invalid";
}
if(content.value=='' || email.value.length>500) {
obj.innerHTML = "Content of length must between 1 to 60 words";
return false;
}
return true;
}

/* random right banner */
function rnd() {
	rnd.seed = (rnd.seed*9301+49297) % 233280;
	return rnd.seed/(233280.0);
};

function rand(number) {
	return Math.ceil(rnd()*number);
};

function rightRandomBanner() {
	rnd.today=new Date();
	rnd.seed=rnd.today.getTime();
	var intn = 1;
	var url = new Array(intn);
/*		url[1] = '/shoes.php';
		url[2] = '/categories/Health-Beauty';
		url[3] = '/MBTshoes.php';
		url[4] = '/ThanksgivingDay.php';
		url[5] = '/17shoes.php';
*/
		url[1] = 'http://www.eshopwalk.com/categories/Movies-DVD/';
		
		
	var num = rand(intn);
	var str = '<a href=' + url[num] + '>';
		str += '<IMG SRC="/product_images/uploaded_images/right/right_banner_' + num + '.jpg" WIDTH="174" HEIGHT="303"></a>';
		
	document.write(str);
}



