jQuery.preloadImages = function(){
	for(var i = 0; i<arguments.length; i++){
		jQuery("<img>").attr("src", arguments[i]);
	}
}

var fa=true;
var sat = new Array();
var i = 0;
var aadtb;
$(document).ready(function(){
	
	//set some options 
	$('.addtext').hide();
	$('.toCart').hide();
	window.active = false;
	window.file = false;
	
	if(navigator.userAgent.indexOf('AOL') !== -1 || navigator.userAgent.indexOf('America Online') !== -1){

		$aolWarning = '<p class="error">You are using an AOL based browser.</p><p>&nbsp;</p><p class="error">Unfortunately this browser is not supported.</p><p>&nbsp;</p><p class="error">We recommend downloading Firefox, <a href="http://download.mozilla.org/?product=firefox-3.5.7&os=win&lang=en-GB">download here</a>.</p><p>&nbsp;</p><p class="error">Magic International Limited ("We") are not responsible for the content of external Internet sites.</p><p>&nbsp;</p><p class="error">Please see Terms and Conditions.</p>';
		
		$('#wholePage .content').css({'width':340,'height':240,'z-index':1000});
		
		$('#wholePage .content .content').css({'width':300,'height':210,'z-index':1001}).html($aolWarning);
		$('#confirmButton,#tryAgain').remove();
		$('#wholePage').show().css({'height':900,'z-index':999});
	}
	
	$.preloadImages("/_images/ex1.png","/_images/ex2.png","/_images/ex3.png","/_images/ex4.png","/_images/application/roundededges.png");
	
	$('.pBut').click(function()
	{
		window.aspect_ratio = .745;
		$('#sh').attr({src: '/_images/application/portrait.png'});
		$.b.orientation({read: 'write', or: 'portrait'});
		$('#orientation').html('portrait');
		$.b.design({read:'write', obj:$(this)});
		$.b.slide({dir:'left', pos:'960px'});
		$('#video object').hide();
		$('.aitm #circle-trace').attr({'shape':'oval'});
		$('.aitm #roundededges').attr({'shape':'square'});
		$('#dpre img').attr({src:'/_images/balloons/'+$(this).attr('id')+'.png'});
		$('.aitm #circle-trace img').attr({src:'/_images/application/smalloval.png'}).css({'display':'block','marginLeft':0});
		$('.aitm #roundededges img').attr({src:'/_images/application/smallrsquare.png'}).css({'display':'block'});
	});
	
	$('.lBut').click(function()
	{
		window.aspect_ratio = .745;
		$('#sh').attr({src: '/_images/application/landscape.png'});
		$.b.orientation({read: 'write', or: 'landscape'});
		$('#orientation').html('landscape');
		$.b.design({read:'write', obj:$(this)});
		$.b.slide({dir:'left', pos:'960px'});
		$('#video object').hide();
		$('#dpre img').attr({src:'/_images/balloons/'+$(this).attr('id')+'.png'});
		$('.aitm #circle-trace').attr({'shape':'oval'});
		$('.aitm #roundededges').attr({'shape':'square'});
		$('.aitm #circle-trace img').attr({src:'/_images/application/hori-oval.png'}).css({'marginLeft':-10,'marginTop':10,'display':'block'});
		$('.aitm #roundededges img').attr({src:'/_images/application/hori-square.png'}).css({'marginLeft':10,'marginTop':10,'display':'block'});
	});
	
	$('.rBut').click(function()
	{
		$('.smalls').attr({shape:'round'});
		$('#sh').attr({src: '/_images/application/landscape.png'});
		$.b.orientation({read: 'write', or: 'round'});
		$('#orientation').html('round');
		$.b.design({read:'write', obj:$(this)});
		$.b.slide({dir:'left', pos:'960px'});
		$('#video object').hide();
		$('#dpre img').attr({src:'/_images/balloons/'+$(this).attr('id')+'-round.png'});
		$('.aitm #circle-trace img').attr({'src':'/_images/application/round.png'}).css({'marginLeft':30});
		$('.aitm #roundededges img').hide();
		$('#shape').html('round');
		window.aspect_ratio = 1;
	});
	
	$('#er .close').click(function(){
		$('#er').empty().hide();
		$('.relative').addClass('relative');
	});
	
	$('#fileU').change(function(){
		$('#fakeField').attr({value:$(this).val()});							
	 }).focus(function(){$('#fakeField').attr({value:$(this).val()});}).blur(function(){$('#fakeField').attr({value:$(this).val()});});
		
	$('#slider').slider({
		slide:function(event,ui){
			var max_w = $('#imgPhoto').width(); 
			var max_h = $('#imgPhoto').height();
			//make sure it stays a square
			if(window.aspect_ratio == 1){
				if(parseInt($('#iw').html()) > parseInt($('#ih').html())){
					max_w = $('#imgPhoto').height(); 
					max_h = $('#imgPhoto').height();
				}
				else
				{
					max_w = $('#imgPhoto').width();
                                        max_h = $('#imgPhoto').width();
				}
			}
			var c = window.api.tellSelect();
			if ($('#orientation').html() == 'portrait') {
               			var new_h = Math.round(ui.value / 100 * max_h);
                		var new_w = Math.round(new_h * window.aspect_ratio);
            		}
			else {
                		var new_w = Math.round(ui.value / 100 * max_w);
                		var new_h = Math.round(new_w * window.aspect_ratio);
            		}     
			if ($('#orientation').html() == 'round') {
				if(parseInt($('#iw').html()) > parseInt($('#ih').html())){
					var new_w = Math.round(ui.value / 100 * $('#imgPhoto').height()); 
					var new_h = Math.round(ui.value / 100 * $('#imgPhoto').height());
				}
				else{
					var new_w = Math.round(ui.value / 100 * $('#imgPhoto').width()); 
					var new_h = Math.round(ui.value / 100 * $('#imgPhoto').width());
				}
			}		
			var x1 = c.x + Math.floor( ( c.x2 - c.x - new_w ) / 2);
			var y1 = c.y + Math.floor( ( c.y2 - c.y - new_h ) / 2);
			var x2 = x1 + new_w;
			var y2 = y1 + new_h;
			if (x1 < 0) {
				x1 = 0;
				x2 = new_w;
			}
			if (y1 < 0) {
				y1 = 0;
				y2 = new_h;
			}
			if (x2 > max_w) {
				x2 = max_w;
				x1 = max_w - new_w;
			}
			if (y2 > max_h) {
				y2 = max_h;
				y1 = max_h - new_h;
			}
			window.api.setSelect([x1,y1,x2,y2]);
		},
		max:93,
		min: window.initial_slider_pos,
		value: window.initial_slider_pos	
	});
		
	$('a[rel=external]').click(function(){
		$(this).attr({title: $(this).attr('title')+' [ This will open in a new window ]'});
		window.open($(this).attr('href'));
	});
	
	$('.smalls').click(function(){
		if(window.file){
			$('#shape').html($(this).attr('shape'));
			if($('#crop-shape-tool').attr('src')){
				$('#crop-shape-tool').attr({'src':'/_images/application/'+$(this).attr('id')+'.png'});
				if($.browser.msie && $.browser.msie.version==7){
					$.b.ieseven();
				}
			}
			else{
				$.b.cCropD({des:$(this).attr('id')});
				if($.browser.msie && $.browser.version==7){
					$.b.ieseven();
				}
			}
			$.post('/update_balloon_stuff.php',{'design':$('#design').html(),'orientation':$('#orientation').html(),'shape':$('#shape').html()});
			window.active = true;
			$('#crop-shape-tool').attr({src:'/_images/application/'+$(this).attr('id')+'.png'});
			return true;
		}
		else{
			return false;
		}
	});
	
	$('#cropnow').click(function(){
		
		//check if the crop is active or not.
		if(window.active !== true){
			return false;
		}

		$('.relative').removeClass('relative').addClass('tempRel');
		$('#er').show().css({left:940}).html('<p class="clear" style="margin-top:250px; margin-left:80px; text-align:center;">Loading.. Please Wait</p><br clear="both" /><img class="loading" src="/_images/application/loading.gif" style="margin-left:440px;"  />');
		
		$.b.save(function(data){
			if(data=='saved'){
				$('#er').hide();
				$('.relative').addClass('relative');
				$('#home_page #wholePage').show().css({'z-index':1000, 'height':900});
				
				if($('#orientation').html() == 'portrait'){
					//dimensions for wholepage content
					$('#wholePage .content')
					  .css({'width':340,'height':480});
					  $('#wholePage .content .content')
					  .css({'width':300,'height':420});
				}
				else if($('#orientation').html() == 'round'){
					//dimensions for wholepage content
					$('#wholePage .content')
					  .css({'width':370,'height':410});
					  $('#wholePage .content .content')
					  .css({'width':330,'height':340});
				}
				else{
					//dimensions for wholepage content
					$('#wholePage .content')
					  .css({'width':600,'height':560});
					  $('#wholePage .content .content')
					  .css({'width':560,'height':500});
				}
				
				
				$('#home_page #wholePage .prev').attr({src:'/_images/pictures/'+$('#pid').html()+'/cropped.png'});
				return true;
				
			}//if
			else{
				//dimensions for container
				$('#wholePage')
				 .css({'height':1200,'z-index':1000})
				 .show()
				;
				
				//remove the un-needed button
				$('#confirmButton').remove();
				
				//dimensions for wholepage content
				$('#wholePage .content')
				  .css({'width':300,'height':120})
				;
				
				//$html = '<p class="error">There was an error saving your image. Click <a href="/index.php">here</a> to try again</p>';
				$html = '<p class="error">'+data+'</p>';
				//inner content of lightbox
				$('#wholePage .content .content')
				  .css({width:270,height:60})
				  .html($html)
				;
			}//else
		});
		
	});
	
	$('.minus').click(function(){
		var cid=$(this).attr('id');
		if(Number($('#q'+cid).html())==1){
			return false;
		}//if
		else{
			$('#q'+cid).html(Number($('#q'+cid).html())-1);
			$.post('/_core/_func/balloon.php',{'minus':'1','id':cid},function(data){if(data!=='set'){alert(data);}});
		}//else
		return false;
	});
	
	$('.plus').click(function(){
		var cid=$(this).attr('id');
		$('#q'+cid).html(Number($('#q'+cid).html())+1);
		$.post('/_core/_func/balloon.php',{'plus':'1','id':cid},function(data){if(data!=='set'){alert(data);}});
		return false;
	});
		
	$('.remove').click(function(){
		var id=$(this).attr('id');
		$.post(
			   '/_core/_func/_pre/session.php',
			   {delet:'item',id:$(this).attr('id')},
			   function(data){
				   if(data=='deleted'){
					   $('#item_'+id).fadeOut(1000);
				   }
				   else{
					   alert(data);
				   }
				}
		);
	});
	
	$('.addaddresses').click(function(){
		$('#todocont').animate({top: -239},600);
	});
	
	$('#view-examples').click(function(){
		$('.examples #cont').fadeOut(1000);
		$.get('/_includes/examples.php',function(data){
			$('.examples').append('<div id="cont">'+data+'</div>');
		});
		$('.examples .Title').html('Examples of designs');
	});
	
	$('.login').click(function(){
		$('#login_form').slideDown(1000);
	});
	
	$('#login_form img').click(function(){
		if($('#username').val() =='' || $('#password').val() ==''){
			return false;
		}
		$.post('/_core/_func/user.php',
				{
					username:$('#username').val(),
					password:$('#password').val(),
					action:'login'
				},
				function(data){
					
					if(data=='success'){
						$.b.GreenTick("login");
						$('#login_form').slideUp(1000);
						window.location = '/cart/';
					}
					else{
						//The user input wrong details
						//dimensions for container
						$('#wholePage')
						 .css({height:800})
						 .show()
						;
						
						//remove the un-needed button
						$('#confirmButton').remove();
						
						//dimensions for wholepage content
						$('#wholePage .content')
						  .css({width:300,height:120})
						;
						
						$html = '<p class="error">'+data+'</p>';
						
						
						//inner content of lightbox
						$('#wholePage .content .content')
						  .css({width:270,height:60})
						  .html($html)
						;
					}
				});
	});
	
	$('#cart_page #tryAgain').click(function(){
		$('#wholePage').hide();
	});
	
	$('#resetToDo').click(function(){
		$('#todocont').animate({top:1},600);
	});
	
	$('.addaddressesbox #addAddressSubmit').click(function(){
		if($('#firstnames').val() == '' || $('#address1').val() == '' || $('#town').val() == '' || $('#postcode').val() == ''){
			alert('All fields but surname and telephone are require');
			return false;
		}
		$.post('/_core/_func/user.php',
				{
					firstnames:$('#firstnames').val(),
					surname:$('#surname').val(),
					telephone:$('#telephone').val(),
					address1:$('#address1').val(),
					address2:$('#address2').val(),
					town:$('#town').val(),
					postcode:$('#postcode').val()
				},
				function(data){
					if(data=='success'){
						$.b.GreenTick("addaddress");
						$('#firstnames').val('');
						$('#telephone').val('');
						$('#address1').val('');
						$('#address2').val('');
						$('#town').val('');
						$('#todocont').animate({top:1},600);
					}
					else{
						//dimensions for container
						$('#wholePage')
						 .css({height:800})
						 .show()
						;
						
						//remove the un-needed button
						$('#confirmButton').remove();
						
						//dimensions for wholepage content
						$('#wholePage .content')
						  .css({width:300,height:120})
						;
						
						$html = '<p class="error">'+data+'</p>';
						$('#wholePage .content')
						  .css({'marginTop':0});
						//inner content of lightbox
						$('#wholePage .content .content')
						  .css({width:270,height:60})
						  .html($html)
						;
					}
				});
	});
	
	$('.assaddresses').click(function(){
		$.get(
				'/_includes/cart/assign.php',
				function(data){
					$('#assign_addresses').html(data);
				}
		);
		$('#todocont').animate({top:-480},600);
	});
	
	$('#assign_addresses img').click(function(){
		$.post('/_core/_func/user.php',
				{
					name:$('#name').val(),
					address1:$('#address1').val(),
					address2:$('#address2').val(),
					postcode:$('#postcode').val(),
					country:$('#country').val(),
					address2:$('#address2').val(),
					description:$('#decription').val()
				},
				function(data){
					if(data=='nosuccess'){
						$.b.GreenTick("assaddress");
						$('#todocont').animate({top:1},600);
					}
					else{
						alert(data);
					}
				});
	});
	
	$('#addanother').click(function(){
		$('#er').show().html();
	});
	
	/*slide and reset the cropper */
	$('#slideappleft').click(function(){
		if(window.api){
			window.api.destroy();
			$('#slider').slider('option', 'value', 33);
			
		}
		$('#video object').show();
		$.b.slide({
			dir:'right',
			pos:0
		});
	});
	
	$('#custom_text_holder input').focus(function(){
		var id = $(this).attr('id');
		$('.active').fadeOut(100).removeClass('active');
		setTimeout(function(){$('#custom_text_editors .'+id+', #custom_text_editors .'+id+' div').fadeIn(100).addClass('active');},500);				
	});

	$('#home_page #confirmButton').click(function(){
		window.location = '/addtext/';
	});
	
	$('#home_page #tryAgain').click(function(){
		$('body').css({overflow:'auto'});
		$.post('/removeBalloon.php',{'id':$('#pid').html()});
		$('#home_page #wholePage').hide();
	});
	
	$('#cart #preview').click(function(){
		var id = $(this).attr('src');
		$('#wholePage .content .content').html('<img style="width:100%; max-height:100%;" src="'+id+'" />');
	});
	
	$('.shoppingcart #preview').click(function(){
		$id = $(this).attr('class');
		$src = $(this).attr('src');
		
		window.download = $src;
		
		$('#wholePage').show().height(900);
		var or = $(this).attr('or');
		if(or == 'portrait'){
			//dimensions for wholepage content
			$('#wholePage .content')
			  .css({'width':340,'height':480});
			  $('#wholePage .content .content')
			  .css({'width':300,'height':420});
		}
		else if(or == 'round'){
			//dimensions for wholepage content
			$('#wholePage .content')
			  .css({'width':540,'height':510});
			  $('#wholePage .content .content')
			  .css({'width':500,'height':450});
		}
		else{
			//dimensions for wholepage content
			$('#wholePage .content')
			  .css({'width':600,'height':450});
			  $('#wholePage .content .content')
			  .css({'width':560,'height':380});
		}
		//change the default buttons
		$('#confirmButton').attr({'src':'/_images/download.png','class':'download','id':''}).wrap('<a href="/download.php?file='+$src+'" target="_blank"></a>').css({marginTop:10});
		$('#tryAgain').attr({src:'/_images/application/APPROVE.png'}).wrap('<a href="/cart/"></a>');
		
		//image preview
		$newImg = $('<img />')
					.attr({'src':$src,'id':'preview'})
					.css({'width':'90%','height':'90%','marginLeft':'auto','marginRight':'auto','display':'block','float':'none'})
		;
		
		//output everything
		$('#wholePage .content .content')
		 .html($newImg)
		;
	});
	
	$('.login_text').click(function(){
		$(this).hide();
		$.post('/_core/_func/user.php',{logout:'true'},function(data){window.location = window.location;});

	});
	
	$('.datepicker').datepicker('destroy').datepicker({
		dateFormat: 'dd-mm-yy',
		firstDay: 1,
		beforeShowDay: function(date){
			if( date.getDay() == 1 || date.getDay() == 0 ) return [false];
			else if(date.getDay() == 6){
				window.sat[i++] = date.getDate();
				return [true];
			}
			else return [true]; 
		},
		onSelect:function(dateText, inst){
			if(dateText.substr(0,2) == window.sat[0] || dateText.substr(0,2) == window.sat[1] || dateText.substr(0,2) == window.sat[2] || dateText.substr(0,2) == window.sat[3] || dateText.substr(0,2) == window.sat[4])
			{
				$('.deliverymethod[wo='+$(this).attr('wo')+'] option').each(function(){
					//$('option[value=1]').attr({'disabled':'disabled'});
					$('option[value=2]').attr({'disabled':'disabled'});
					//$('option[value=3]').attr({'selected':'selected'});
				});
				$('.deliverymethod[wo='+$(this).attr('wo')+'] option').focus();
			}
			else{
				$('.deliverymethod[wo='+$(this).attr('wo')+'] option').each(function(){
					//$('option[value=1]').attr({'disabled':''});
					$('option[value=2]').attr({'disabled':''});
				});
			}
			$(this).attr({'value':dateText});
			$.post(
				'/update_balloon_date.php',
				{'id':$(this).attr('wo'),'date':$(this).val()},
				function(data)
				{
					if(data !== 'set')
						alert('There was an unexpected error, please try again.');
						//alert(data);
				}
			);
		}		
	});


	$('.deliverymethod').change(function(){
			$.post(
				'/update_pay_method.php',
				{'id':$(this).attr('wo'),'method':$(this).val()},
				function(data)
				{
					if(data !== 'set')
						//alert('There was an unexpected error, please try again.');
						alert(data);
				}
			);
		}).focus(function(){
			$.post(
                                '/update_pay_method.php',
                                {'id':$(this).attr('wo'),'method':$(this).val()},
                                function(data)
                                {
                                        if(data !== 'set')
                                                //alert('There was an unexpected error, please try again.');
                                                alert(data);
                                }
                        );
		});
	
	$('select').click(function(){
		$('option').find('option').css({'width':220});
	});

	$('#creditcards').click(function(){
		$('.datepicker').each(function(i){
			if($(this).val() == '' || $(this).val() == 'Select date')
			{
				$(this).focus();
				window.fa = false;
			}
			else{
				window.fa = true;
			}
		});
		if(!window.fa)
			return false;
		else
			window.location = 'checkout.php';
	});
	
});//what's up doc??

function show_loading(time){
	$('.relative').removeClass('relative').addClass('tempRel');
	$('#er').show().css({left:940}).html('<p class="clear" style="margin-top:250px; margin-left:450px;">Please Wait...</p><img class="loading" src="/_images/application/loading.gif" style="margin-left:440px;"  /><br /><p class="clear" style="margin-left:470px;">Loading..</p>');
}

Array.prototype.in_array = function(p_val) {
	for(var i = 0, l = this.length; i < l; i++) {
		if(this[i] == p_val) {
			return true;
		}
	}
	return false;
}

if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun /*, thisp*/)
  {
    var len = this.length >>> 0;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        fun.call(thisp, this[i], i, this);
    }
  };
}
function finalWholebox()
{
	$('#confirmButton, #tryAgain').hide();
	$('#wholePage .content')
        .css({'width':600,'height':450});

        $('#wholePage .content .content')
        .css({'width':560,'height':380});
	
	$('#wholePage').html('Thank you for your payment.<br />We will deliver your balloon(s) as soon as possible.<br /><br /><a href="/index.php"><img alt="Make another balloon" src="/_images/application/makeanotherballoon.png"></a>').show();
}
