var offerTotal=0;
var loading;
var loading2;

function getPrice(total,carry,level,voucher,transName){
	//loading2.show();
	var order_total=Number(total+carry).toFixed(2);
	var temp_charge=(total+carry)*0.039;
	var charge=Number(temp_charge).toFixed(2);
	if(level==3){
		order_total=(Number(temp_charge)+Number(order_total)).toFixed(2);
		$('#bank_charge').html(charge);
		$('#order_charge').val(charge);
	}
	if(voucher!=0){
		order_total=(Number(order_total)-Number(voucher)).toFixed(2);
	}
	$('#shipping_charge').html(Number(carry).toFixed(2));
	$('#grand_order_total_price').html(order_total);
	$('#order_carry').val(Number(carry).toFixed(2));
	$('#order_total_price').val(order_total);
	$('#order_trans').val(transName);
	//loading2.hide();
	return true;
}

function changePrice(cid,weight,total,products){
	//loading.show();
	$.ajax({
        url:'get_method.php',  
		type: 'POST',
		data: "cid="+cid+"&weight="+weight+"&total="+total+"&products="+products,
        success:function(datas){
			$('#shipping_method').html(datas);
			//loading.hide();
		}            
    });
}

function addToCart(productId){
	$.ajax({
        url:'order_add.php',  
		type: 'POST',
		data: "status=1&method=quick&p_spec=1&p_id="+productId,
        success:function(datas){
			var image=$('#image_'+productId).offset();
			var cart=$('#cart').offset();
			$('#image_'+productId).before('<img width="150" height="150" border="0" src="' + $('#image_'+productId).attr('src') + '" id="temp" style="position: absolute; top: ' + image.top + 'px; left: ' + image.left + 'px;" />');
			params={
				top:cart.top + 'px',
				left:cart.left + 'px',
				opacity:0.5,
				width:$('#cart').width(),  
				height:$('#cart').height()
			};		
			$('#temp').animate(params,'slow',false,function(){
				$('#temp').remove();
			});
			//$("html,body").animate({scrollTop:0},600);
		}            
    });
}

function getTransName(value){
	alert(value);
	$("#order_trans").val(value);
}

function addToCart2(productId,amount){
	$.ajax({
        url:'order_add.php',  
		type: 'POST',
		data: "status=2&method=quick&p_spec=1&p_id="+productId+"&amount="+amount,
        success:function(datas){
			alert(datas); 
			$('#offer_'+productId+' .buybutton').css({'background-image':'url(../images/button_01.jpg)'}); 
			$('#offer_'+productId+' a').attr('disabled','true');
			$("#check_out").css('display','');
			offerTotal++;
        }            
    });
	
	$.ajax({
        url:'getOfferTotal.php',  
        success:function(data){
			if(data==offerTotal){
				$("#submitoffer_btn a").attr('disabled','true');	
			}		
        }            
    });
}

function addProducts(){
	document.forms['formps'].submit();
}

function submitform(currform){
	document.forms[currform].submit();
}

function submitOffer(){
	openAllOfferState();
	var isok=checkoffer();
	if(isok==true){
		document.forms['offer'].submit();
	}
}


function checkDegital(obj){
	var target=$(obj);
	var patrn=/^([1-9])+([0-9])*$/; 
	if(target.val()!=""){
		if (!patrn.exec(target.val())){		
			target.val('');
			target.focus();
		}
   }
}

function checkDegital2(obj){
	var target=$(obj);
	var patrn=/^([0-9])+.?[0-9]*$/; 
	if(target.val()!=""){
		if (!patrn.exec(target.val())){		
			target.val('');
			target.focus();
		}
   }
}

/* function getTransportPrice(str_weight){
	var target=document.getElementsByName("offerquantity[]");
	var arr_weight=new Array();
	arr_weight=str_weight.split(',');
	var weight_len=arr_weight.length;
	var total_weight=0;
	for(var i=0;i<weight_len;i++){
		total_weight+=Number(arr_weight[i])*Number(target[i].value);
	}
	total_weight=Number(total_weight).toFixed(2);
	$('#total_weight').html(total_weight);
} */

function getTransportPrice(){
	var target=document.getElementsByName("offerquantity[]");
	var str_weight=$("#str_weight").html();
	var target_len=target.length;
	var str_quantity='';
	for(var i=0;i<target_len;i++){
		str_quantity+=target[i].value+',';
	}
	var sn=$("#sn").val();
	$.ajax({
            url:"getTransportPrice.php",
			type:'post',
			data:{weight:str_weight,quantity:str_quantity,sn:sn},		
            success:function(data){
				var total_weight=$("#total_weight");
				total_weight.html('');
				total_weight.html(data);
				$("#offer_grand_total").val(data);
				$("#carry").val(data);
            }            
		});
}


function checkoffer(){
	var price=document.getElementsByName("offerPrice[]");
	var quantity=document.getElementsByName("offerquantity[]");
	var price_len=price.length;
	for(var i=0;i<price_len;i++){
		if(price[i].value==''){
			alert("Please input your offer price!");
			price[i].focus();
			return false;
		}
		if(quantity[i].value==''){
			alert("Please input your quantity!");
			quantity[i].focus();
			return false;
		}
	}
	return true;
}


function closeOfferState(state){
	var arr=new Array();
	arr=state.split(',');
	//alert(arr.join());
	if(state!=''){
		var price=document.getElementsByName("offerPrice[]");
		var quantity=document.getElementsByName("offerquantity[]");
		var price_len=price.length;
		for(var i=0;i<price_len;i++){
			if(arr[i+2]=='1'){
				price[i].disabled=true;
				quantity[i].disabled=true;
			}		
		}
	}
}


function openOfferState(position){
	var price=document.getElementsByName("offerPrice[]");
	var quantity=document.getElementsByName("offerquantity[]");
	var price_len=price.length;
	for(var i=0;i<price_len;i++){
		if(i==position){
			price[i].disabled=false;
			quantity[i].disabled=false;
		}
	}
}


function openAllOfferState(){
	var price=document.getElementsByName("offerPrice[]");
	var quantity=document.getElementsByName("offerquantity[]");
	var price_len=price.length;
	for(var i=0;i<price_len;i++){
		price[i].disabled=false;
		quantity[i].disabled=false;
	}
}

function RemainTime(){
    var iDay,iHour,iMinute,iSecond;
    var sDay="",sHour="",sMinute="",sSecond="",sTime="";
    if (iTime >= 0){
        iDay = parseInt(iTime/24/3600);
        if (iDay > 0){
            sDay = iDay + " Days ";
        }
        iHour = parseInt((iTime/3600)%24);
        if(iHour > 0){
            sHour = iHour + " Hours ";
        }
        iMinute = parseInt((iTime/60)%60);
        if (iMinute > 0){
            sMinute = iMinute + " Minutes ";
        }
        iSecond = parseInt(iTime%60);
        if (iSecond >= 0){
            sSecond = iSecond + " Seconds ";
        }
		sTime="<span style='font-weight:bold;color:red;font-size:13px;text-align:right;'>Valid for " + sDay+sHour+sMinute +sSecond+"</font>";
        if(iTime==0){
           cancelOffer();
        }else{
            Account = setTimeout("RemainTime()",1000);
        }
        iTime=iTime-1;
    }else{
        
    }
    document.getElementById(CID).innerHTML = sTime;
}

function goprepage(){
	history.back();
}

function cancelOffer(){
	//var offer_id=document.getElementById("offer_id").value;
	$.ajax({
        url:"deleteoffer.php",
			type:'get',
			data:{action:'timeout'},		
            success:function(data){
				alert('Offer time is out!');
				location.href=location.href;
            }            
		});
}

function showlogin(val){
	if(val==''){
		alert("Please login first!");
	}
}

function addoffer(pid){
	location.href='addoffer.php?hash=abcdefg&p_id='+pid;
}

function checkorder(sn,country,weight,subtotal,totalvoucher){
	$.ajax({
        url:"getCharge.php",
		type:'post',
		data:{sn:sn,country:country,weight:weight,subtotal:subtotal,totalvoucher:totalvoucher},		
        success:function(data){
			//alert(data);
			var arr=data.split("-");
			$("#shipping_method").html(arr[0]);
			$("#shipping_desc").html(arr[1]);
			$("#shipping_charge").html(arr[2]);
			//$("#order_total").val(arr[4]);
			$("#order_total_price").val(arr[4]);			
			$("#order_charge").val(arr[3]);
			$("#order_carry").val(arr[2]);
			$("#grand_order_total_price").html(parseFloat(arr[4]).toFixed(2));
			if(totalvoucher!=0){
				$("#orignal_order_total_price").html(arr[5]);
			}			
			var bank_charge=parseInt(arr[3]);
			if(bank_charge!=0){
				$("#bank_charge").html(arr[3]);
			}
        }            
	});
}

var prePid=0;

function sum(level,type){
	if(type==2){
		var voucher_price=document.getElementsByName('voucher[]');
		var voucher_len=voucher_price.length;
		var sum_voucher=0;
		for(var i=0;i<voucher_len;i++){
			sum_voucher+=parseFloat(voucher_price[i].value);
		}
		$("#voucher_total").html(sum_voucher.toFixed(2));	
	}
	
	var price=document.getElementsByName('price[]');	
	var amount=document.getElementsByName('amount[]');
	var pid=document.getElementsByName('pid[]');
	var pid_len=pid.length;
	
	var position=0;
	var carry=$("#carry").val();
	var carry_total=parseFloat(carry);
	
	
	
	var sum=new Array();
	for(var i=0;i<pid_len;i++){
		sum[i]=parseFloat(price[i].value)*parseInt(amount[i].value);
	}
	perPid=pid[0].value;
	var subtotal=0;
	
	var result=new Array();
	for(var k=0;k<pid_len;k++){
		if(pid[k].value==perPid){
			subtotal+=sum[k];
		}else{
			perPid=pid[k].value;
			position++;
			subtotal=sum[k];
		}
		result[position]=subtotal.toFixed(2);
	}
	//alert(result.join('--'));
	var result_len=result.length;
	var sub_total=0;
	for(var j=0;j<result_len;j++){
		var index=j+1;
		$("#subtotal_"+index).html(result[j]);
		sub_total+=parseFloat(result[j]);
	}
	
	$("#sub_total").html(sub_total.toFixed(2));
	var total=(carry_total+sub_total).toFixed(2);	
	var bank_charge=(total*0.039).toFixed(2);
	$("#bank_charge").html(bank_charge);
	if(level==3){
		var finaltotal=(parseFloat(total)+parseFloat(bank_charge)).toFixed(2);
	}else{
		var finaltotal=(parseFloat(total)).toFixed(2);
	}
	$("#grand_total").html(finaltotal);
	
	if(type==2){
		finaltotal=(finaltotal-sum_voucher).toFixed(2);		
	}
	$("#order_total").html(finaltotal);
}

function checknumber(obj,value){
	var target=$(obj);
	var patrn=/^([0-9])+.?[0-9]*$/; 
	if(target.val()!=""){
		if (!patrn.exec(target.val())){		
			target.val(value);
			target.focus();
			return false;
		}else{
			return true;
		}
   }else{
		target.val(value);
   }
}

function trim(str){ //删除左右两端的空格
	return str.replace(/(^\s*)|(\s*$)/g, "");
}

function checkExchange(){
	var barcode=$("#exchangecode").val();
	if(trim(barcode)==''){
		//alert("Please input your exchange code.");
		$("#exchangeTip").html('Input exchange code.');
		$("#exchangecode").focus();
		return false;
	}
	$.ajax({
        url:'doexchange.php?action=validate',  
		type: 'POST',
		data: "barcode="+barcode,
        success:function(datas){
			var arr=datas.split('-');
			if(arr[0]==0){
				$("#exchangeTip").html(arr[1]);
				return false;
			}else{
				$("#exchangeTip").html('');
				document.cart.action='doexchange.php';
				document.forms['cart'].submit();
			}			
        }            
    });
}

function newgdcode(obj,url) {
	obj.src = url+ '?nowtime=' + new Date().getTime();
	//后面传递一个随机参数，否则在IE7和火狐下，不刷新图片
}

function closeLoadding(){
	$.unblockUI();
}

var checkCredit=true;

function checkinput(form){
	showLoadding();
	if(form.m_name.value==""){
		closeLoadding();
        alert("Please input your first name!");
        form.m_name.focus();
        return false;
    }	
	if(form.m_name2.value=="") {
		closeLoadding();
		alert("Please input your second name!");
		form.m_name2.focus();
        return false;
    }
		
	if(form.m_email.value==""){
		closeLoadding();
        alert("Please input your email!");
        form.m_email.focus();
        return false;
    }
	
	if(form.m_tel.value==""){
		closeLoadding();
		alert("Please input your phone number!");
		form.m_tel.focus();
        return false;
    }
		
	if(form.addr.value==""){
		closeLoadding();
        alert("Please input your address!");
        form.addr.focus();
        return false;
    }
		
	if(form.Zip.value==""){
		closeLoadding();
        alert("Please input your zip code!");
        form.Zip.focus();
        return false;
    }
		
	if(form.City.value=="") {
		closeLoadding();
        alert("Please input your city!");
        form.City.focus();
        return false;
    }
				
	if(form.Canton.value=="") {
		closeLoadding();
        alert("Please input your canton!");
        form.Canton.focus();
        return false;
	}
	
	if(checkCredit==true){
		return checkCreditCard();
	}
	return true;
}

function checkVoucherInput(){
	showLoadding();
	if(checkCredit==true){
		return checkCreditCard();
	}
	return true;
}


function showLoadding(){
	$.blockUI(
		{css:{
			border:'none', 
			padding:'2px', 
			backgroundColor:'#ffffff', 
			'-webkit-border-radius':'10px', 
			'-moz-border-radius':'10px', 
			opacity:0.6, 
			color:'#000000'
		} 
		}
	); 
}

function checkCreditCard(){
	var tmp=true;
	if($("#cardNumber").val()==""){
		closeLoadding();
        alert("Please input Credit Card Number!");
		$("#cardNumber").focus();
		tmp=false;
        return false;
	}else{
		tmp=true;;
	}
	if($("#cardCvv").val()==""){
		closeLoadding();
        alert("Please input Credit Card's CVV!");
        $("#cardCvv").focus();
		tmp=false;
        return false;
	}else{
		tmp=true;
	}
	return tmp;
}
