var documentBase="https://www.fivetenstudio.com/";
var Interval;
var trigger=false;
var canceled=true;
var counter=0;
var myPopUp;
var openedDetail;
var cart = Class.create();
cart.prototype = {
	items:new Array(),
	total:0,
	initialize: function() {
		
	},
	add: function(index,productId) {
		if(this.items[index]==undefined){
			this.items[index]=productId;
			output ='<div style="display:none;" id="wrapper'+index+'" class="fl h0 cartRow"><div>\
				         					<div class="fl p10"><img class="hand" onclick="javascript:showProduct('+productId+');" src="img/product'+productId+'_icon.jpg" width="50px" height="50px"></div>\
				         					<div class="fl w350 b ml10">'+products[productId]['name']+'</div>\
				         					<div class="fr mr20"><a onclick="javascript:cart.remove('+index+')" id="remove'+index+'" class="remove">remove</a></div>\
				         					<div class="fr b w100">$'+products[productId]['price']+'</div>\
				    </div><div>';
			new Insertion.Bottom('cart',output);
			if($('container').style.display=="none"){
				$('wrapper'+index).show();
				new Effect.BlindDown('container');
			}else{
				Effect.SlideDown('wrapper'+index,{duration:0.5});
			}
			Effect.Fade('addProduct'+index,{duration:0.5,queue: 'end'});
			this.calculateTotal();
		}
	},
	remove: function(index){
		delete this.items[index];
		Effect.Appear('addProduct'+index,{duration:0.5,queue: 'end'});

		
		var cartNotEmpty=false;
		for(var i=0;i<this.items.length;i++){if(this.items[i]!=undefined){cartNotEmpty=true;}}
		if(!cartNotEmpty){
			Effect.BlindUp('container',{afterFinish: function(){Element.remove('wrapper'+index);}});
		}else{
			Effect.SlideUp('wrapper'+index,{duration:0.5,afterFinish: function(){Element.remove('wrapper'+index);}});
		}
		this.calculateTotal();
	},
	calculateTotal:function(){
		this.total=0;
		for(var i=0;i<this.items.length;i++){
			if(this.items[i]!=undefined){
				this.total+= parseInt(products[this.items[i]]['price']);
			}
		}
		var shipping=this.calculateShipping($F('shippingPlace'))
		this.total+=shipping;
		Element.update('orderTotal',this.total);
		Element.update('shippingTotal',shipping);
		return this.total;
	},
	calculateShipping:function(place){
		/*brown toy, grey toy,silkscreen,both toys,sil+toy,all 3*/
		var shipping=new Array();
		shipping['USA'] 		= [160,12,20,28,16,46];
		shipping['HAWAII'] 		= [36,25,30,56,32,84];
		shipping['CANADA'] 		= [24,20,22,58,25,56];
		shipping['EUROPE'] 		= [48,38,48,66,54,88];
		shipping['AUSTRALIA'] 	= [52,45,70,66,65,118];
		var i=0;
		
		if(this.items[i]!=undefined && this.items[i+1]==undefined && this.items[i+2]==undefined){return shipping[place][0];}//product 1
		if(this.items[i]==undefined && this.items[i+1]!=undefined && this.items[i+2]==undefined){return shipping[place][1];}//product 2
		if(this.items[i]==undefined && this.items[i+1]==undefined && this.items[i+2]!=undefined){return shipping[place][2];}//product 3
		if(this.items[i]!=undefined && this.items[i+1]==undefined && this.items[i+2]!=undefined){return shipping[place][3];}//both toys
		if(this.items[i]!=undefined && this.items[i+1]!=undefined && this.items[i+2]==undefined){return shipping[place][4];}//silk + toy
		if(this.items[i]==undefined && this.items[i+1]!=undefined && this.items[i+2]!=undefined){return shipping[place][4];}//silk + toy
		if(this.items[i]!=undefined && this.items[i+1]!=undefined && this.items[i+2]!=undefined){return shipping[place][5];}//all 3
	},
	switchDisableCart:function(form,cart){
		if(form){Form.disable('paymentForm');}
		else{Form.enable('paymentForm');}
		if(cart){
			for(var i=0;i<3;i++){
				if($('remove'+i)!=undefined){Effect.Fade('remove'+i,{queue:'end'});}
				if($('addProduct'+i)!=undefined){Effect.Fade('addProduct'+i);}
			}
		}else{
			for(var i=0;i<3;i++){
				if($('remove'+i)!=undefined){Effect.Appear('remove'+i,{queue:'end'});}
				if($('addProduct'+i)!=undefined){Effect.Appear('addProduct'+i);}
			}
		}
	},
	doPayment:function(type){
		new Element.update('status','');
		var params = Form.serialize('paymentForm')+'&total='+this.total+"&shippingDetails[place]="+$F('shippingPlace');
		for(var i=0;i<this.items.length;i++){
			if(this.items[i]!=undefined){params+= '&products['+this.items[i]+']='+this.items[i];}
		}
		togglePaymentMethod(type);
		if(type=='pp'){
				cart.switchDisableCart(true,true);
				Element.show('cancelRequest');
				$('cancelRequest').enable();
				myPopUp = window.open(documentBase+'ppPayment.php?action=ppAuth&'+params,'mywin','left=0,top=0,width=900,height=500,menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes');
				trigger=false;
				canceled=false;
				Interval=window.setInterval(function () {
				  new Ajax.Request( documentBase+'ppPayment.php',{method:'post', postBody:'action=askForPaypalAuthentificated' , onComplete: cart.paypalStep2});
				},1000);
				Effect.BlindDown('precessingContainer');
		}
		else{
			if(!$('terms2').checked){
				Element.addClassName('errorTermsOfUse2','error');
			}else{
				Element.removeClassName('errorTermsOfUse2','error');
				cart.switchDisableCart(true,true);
				var ajaxReqUrl=documentBase+'ccPayment.php'
				new Ajax.Request( ajaxReqUrl,{method:'post', postBody:params , onComplete: this.doFinalPaymentResponse});
				Element.show('precessingContainer');
			}
		}
	},
	cancelRequest:function(){
		canceled=true;
		$('cancelRequest').hide();
		window.focus();
		myPopUp.close();
		counter=0;
		trigger=false;
		window.setTimeout('canceled=true;', 1000);	
		clearInterval(Interval);
		cart.switchDisableCart(false,false);
		Element.update('status',"You cancelled PayPal Authentication");
		new Effect.BlindUp('precessingContainer',{queue: 'end'});
		new Effect.BlindUp('errorContainer',{queue: 'end'});
		new Effect.BlindUp('review',{queue: 'end'});
	},
	paypalStep2:function(rec){
		if(rec.responseText=='PAYPAL_AUTHENTICATED' && !trigger){
			counter=0;
			trigger=true;
			window.focus();
			clearInterval(Interval);
			var params= 'action=ppReview&total='+cart.total+"&shippingDetails[place]="+$F('shippingPlace');
			for(var i=0;i<cart.items.length;i++){
				if(cart.items[i]!=undefined){params+= '&products['+cart.items[i]+']='+cart.items[i];}
			}
			new Element.update('status','authentification successfull... getting info from paypal');
			new Ajax.Request( documentBase+'ppPayment.php',{method:'post', postBody:params , onComplete: cart.doFinalPaymentResponse});
		}else if(myPopUp.closed){
			window.setTimeout('if(!trigger){cart.cancelRequest();}', 4000);			
		}else if(canceled==false){
			new Element.update('status','waiting for your paypal authentication!');
			counter++;
		}		
	},
	paypalStep2Response:function(rec){

	},
	doFinalPayment:function(){
		var expression = /^[\d\(\)\/ -]{4,13}$/;
		if(!$('terms').checked){Element.addClassName('errorTermsOfUse','error');}else{Element.removeClassName('errorTermsOfUse','error');}
		if(!expression.test($F('payersPhone'))){Element.addClassName('errorPhone','error');}else{Element.removeClassName('errorPhone','error');}
		if($('terms').checked && expression.test($F('payersPhone'))){
			var params= 'action=ppFinal&total='+cart.total+"&shippingDetails[place]="+$F('shippingPlace')+"&phone="+$F('payersPhone');
			new Ajax.Request( documentBase+'ppPayment.php',{method:'post', postBody:params , onComplete: cart.doFinalPaymentResponse});
			cart.switchDisableCart(true,true);
			Element.update('status',"processing final checkout");
			new Effect.BlindDown('precessingContainer',{queue: 'end'});
		}
	},
	doFinalPaymentResponse:function(rec){
		var text = rec.responseText;
		returnArray = text.split('<!>')
		if(returnArray[0]=='errorHash'){
			eval(returnArray[1]);
			if(errors[100]!=undefined){alert('internal error:'+i+errors[100]);}
			for(var i=1;i<=14;i++){
				if(errors[i]!=undefined){Element.addClassName('error'+i,'error');}
				else{Element.removeClassName('error'+i,'error');}
			}
			new Effect.BlindUp('precessingContainer');
			cart.switchDisableCart(false,false);
		}else if(returnArray[0]=='successHash'){
			eval(returnArray[1]);
			new Effect.BlindUp('errorContainer',{queue: 'end'});
			new Effect.BlindUp('ccDetails',{queue: 'end'});
			new Effect.BlindUp('review',{queue: 'end'});
			new Effect.BlindUp('precessingContainer',{queue: 'end'});
			new Effect.BlindUp('paymentContainer',{queue: 'end'});			
			new Effect.BlindDown('successContainer',{queue: 'end'});
		}else if(returnArray[0]=='purchasedHash'){
			eval(returnArray[1]);
			var output="";
			for(a in purchased){output+=purchased[a]+"<br>";};
			Element.update('errorMessage',output);			
			new Effect.BlindUp('ccDetails');
			new Effect.BlindUp('review');
			new Effect.BlindUp('precessingContainer');
			new Effect.BlindDown('errorContainer');
			cart.switchDisableCart(falsw,false);
		}else if(returnArray[0]=='soldOut'){
			cart.switchDisableCart(false,false);
			eval(returnArray[1]);
			var output="";
			for(a in soldOut){output+=soldOut[a]+"<br>";};
			Element.update('errorMessage',output);			
			new Effect.BlindUp('ccDetails',{queue: 'end'});
			new Effect.BlindUp('review',{queue: 'end'});
			new Effect.BlindUp('precessingContainer',{queue: 'end'});
			new Effect.BlindDown('errorContainer',{queue: 'end'});
			
		}else if(returnArray[0]=='customer'){
			eval(returnArray[1]);
			for(var a in customerDetails){if($(a)!=undefined){Element.update(a,customerDetails[a]);}}
			new Effect.BlindUp('errorContainer',{queue: 'end'});
			new Effect.BlindDown('review',{queue: 'end'});
			new Effect.BlindUp('precessingContainer',{queue: 'end'});
			cart.switchDisableCart(false,true);
		}else{
			new Element.update('errorMessage',rec.responseText);
			new Effect.BlindDown('errorContainer');
		}
	},
	clearCart:function(){
		
		this.items.clear();
		
		new Element.update('cart','');
		$('paymentForm').getElements().each(function(element) {
		    if(element.type!='button'){element.value = '';}
		});
	}
}
function showProduct(id){
	openedDetail=id;
	new Effect.Appear('overallLayer');
	new Effect.Appear('detailProduct'+id);
}
function hideProduct(id){
	if(!id){id=openedDetail;}
	new Effect.Fade('detailProduct'+id);
	new Effect.Fade('overallLayer');	
}

function togglePaymentMethod(type){
	if($('ccDetails').style.display=='none' && type=='cc'){new Effect.BlindDown('ccDetails');Element.hide('paypalImage');}
	if($('ccDetails').style.display!='none' && type=='pp'){new Effect.BlindUp('ccDetails');Element.show('paypalImage');}
}

function addNode(parentNode, type, attr)
{
	var n = document.createElement(type);
	for(var i in attr){		
		n.setAttribute(i, attr[i]);
	}
	parentNode.appendChild(n);
	parentNode.appendChild(document.createElement('br'));
	return n;
}
function subscribe( mode ) {
	if( $F('subscribtMail') != null 
			&& $F('subscribtMail') != 'your email' 
			&& isEmailAddr( $F('subscribtMail') ) == true
			) 
		new Ajax.Updater(	'mailinglistContent', 
							documentBase+'mailinglist.php?mode=' + mode + '&email=' + $('subscribtMail').value, 
							{onComplete:function(request){window.setTimeout("Effect.toggle('mailinglist','blind');", 4000);}});
	else {
		$('subscribtMail').style.borderColor = ( !isEmailAddr( $F('subscribtMail')))?'#FF0000':'#000000';
	}
}
function isEmailAddr(email) {
    var result = false;
    var theStr = new String(email);
    var index = theStr.indexOf("@");
    if (index > 0) {
        var pindex = theStr.indexOf(".",index);
        if ((pindex > index+1) && (theStr.length > pindex+1)) {
            result = true;
        }
    }
    return result;
}
function sendContact() {
	if( $F('contact_email') != 'your email' 
		&& isEmailAddr( $F('contact_email') ) == true
		&& $F('contact_message') != 'your message' 
		&& $F('contact_firstName') != 'first name' 
		&& $F('contact_lastName') != 'last name' 
		&& $F('contact_subject') != '' 
		) {
		new Ajax.Updater(	'contactContent', 
							documentBase+'contact.php?from=' + $F('contact_email') + 
								'&subject=' + $F('contact_subject') +
								'&firstname=' + $F('contact_firstName') +
								'&lastname=' + $F('contact_lastName') +
								'&message=' + $F('contact_message'),
							{onComplete:function(request){window.setTimeout("Effect.toggle('contactContainer','blind');", 4000);}});
		}
	else {
		$('contact_firstName_text').style.color =  ( $F('contact_firstName') == 'first name' )?'#F00000':'#000000';
		$('contact_lastName_text').style.color =  ( $F('contact_lastName') == 'last name' )?'#FF0000':'#000000';
		$('contact_email_text').style.color =  ( !isEmailAddr( $F('contact_email')))?'#FF0000':'#000000';
		$('contact_subject_text').style.color =  ( $F('contact_subject') == 'subject' )?'#FF0000':'#000000';
		$('contact_message_text').style.color =  ( $F('contact_message') == '' )?'#FF0000':'#000000';
		}
	}
	
function inputFocus(field){
	field.style.borderColor=(field.style.borderColor=='')?"#999999":"";
	field.style.backgroundColor=(field.style.backgroundColor=='')?"#EFEFEF":"";
}
function toggleBold(field){
	field.style.fontWeight=(field.style.fontWeight=='')?"bold":"";
}