/* BASKET */
$BASKET = {
	item_count: 0,
	
	getItemCount:function() {
		return this.item_count;	
	},
	
	checkboxHandler:function(e) {
		$('.chk_price input:checkbox').attr('checked', false);
		$(e).attr('checked', true);
		$BASKET.calculateOrderForm();
	},	
	add:function(bid, gid) {
		this.item_count++;
		$.getJSON("index.php?id=54&action=addtobasket&bid="+bid+"&gid="+gid, function(data){
			
			var t = $LANGUAGE.getTranslation($LANGUAGE.lang, 'photo_was_added');
			t = t.replace("X", data.length);
			var str = '<div style="display:none;" id="dialog-message" title="'+t+'">';
			//$LOG.console(data);
			for (var i = 0; i < data.length; i++) {
				str += '<div id="basket'+data[i].bid+'" style="border:1px;width:130px;height:140px;float:left"><div style="height:130px"><img src="http://arktiskebilleder.dk/image.php?bid='+data[i].bid+'&max_width=125&max_height=125" alt="'+data[i].bid+'" title="" /></div><div style="height="10px;"><a href="javascript:void(0);" onclick="$BASKET.remove(\''+data[i].bid+'\');"><span class="ui-icon ui-icon-circle-close"></span></a>'+data[i].bid+'</div></div>';
			}
			
			str += '</div>';
			
			$('body').append(str);
			
			var dialog_buttons = {};
			dialog_buttons[$LANGUAGE.getTranslation($LANGUAGE.lang, 'order_photo')] = function() {
				$( this ).dialog( "close" );
				$( this ).dialog( "destroy" );
				$BASKET.showOrderForm();
			};
			
			dialog_buttons[$LANGUAGE.getTranslation($LANGUAGE.lang, 'empty_basket')] = function() {
				$.getJSON("/index.php?id=54&action=clearBasket");
				$( this ).dialog( "close" );
				$( this ).dialog( "destroy" );
			};
			
			dialog_buttons[$LANGUAGE.getTranslation($LANGUAGE.lang, 'continue_reviewing_photos')] = function() {
				$( this ).dialog( "close" );
				$( this ).dialog( "destroy" );
			};
			
			/*
			{
					'Gå til bestilling': function() {
						$( this ).dialog( "close" );
						$( this ).dialog( "destroy" );
					 	$BASKET.showOrderForm();
					},
					'Tøm kurv': function() {
						$.getJSON("/index.php?id=54&action=clearBasket");
						$( this ).dialog( "close" );
						$( this ).dialog( "destroy" );
					},
					'Fortsæt med kigge billeder': function() {
						$( this ).dialog( "close" );
						$( this ).dialog( "destroy" );
					}
			*/
			
			$( "#dialog-message" ).dialog({
		
				width:800,
				height:600,
				modal: true,
				open: function() {
					$(document).bind('click', function() {
						$("#dialog-message").dialog( "close" );
						$("#dialog-message").dialog( "destroy" );	
					});
				},
				buttons: dialog_buttons,
				close: function(event, ui) { 
					$('#dialog-message').remove();
				}
			});
		});
	},
	remove:function(bid) {
		this.item_count++;
		$('#basket'+bid).remove();
		$.getJSON("/index.php?id=54&action=removeFromBasket&bid="+bid);
	},
	removeFromOrderForm:function(bid) {
		this.item_count++;
		$('#basket_items tbody #item_'+bid).remove();
		$.getJSON("/index.php?id=54&action=removeFromBasket&bid="+bid);
		this.calculateOrderForm();
	},
	showOrderForm:function() {
		
		var dialog_buttons = {};
		
		dialog_buttons[$LANGUAGE.getTranslation($LANGUAGE.lang, 'price_list')] = function() {
			$( this ).dialog( "close" );
			$BASKET.showPricelist();
		}; 		
				
		dialog_buttons[$LANGUAGE.getTranslation($LANGUAGE.lang, 'send_order')] = function() {
			$('#form_errors').html('');
					
			if($BASKET.validateForm() == true) {
				$.post("/index.php?id=54&action=submitForm", $("#orderForm").serialize());
				$( this ).dialog( "close" );
				$BASKET.orderSentConfirmationDialog();
			}
		}; 
		
		dialog_buttons[$LANGUAGE.getTranslation($LANGUAGE.lang, 'cancel')] = function() {
			$( this ).dialog( "close" );
		}; 

		/*
		{
					'Annuller':function() {
						$( this ).dialog( "close" );
						
					},
					'Send bestilling':function() {
						
						$('#form_errors').html('');
					
						if($BASKET.validateForm() == true) {
							$.post("/index.php?id=54&action=submitForm", $("#orderForm").serialize());
							$( this ).dialog( "close" );
							$BASKET.orderSentConfirmationDialog();
						}
					}
				}
		*/
		$.get("/index.php?id=54&action=getOrderForm&l="+$LANGUAGE.lang, function(data){
			var str = '<div id="dialog-orderform" title="'+$LANGUAGE.getTranslation($LANGUAGE.lang, 'order')+'" style="display:none;text-align:left"><div style="padding:10px"><div style="float:left">'+$LANGUAGE.getTranslation($LANGUAGE.lang, 'language')+': </div><div style="float:left;padding:2px;" id="langForm-da"><img width="25" src="assets/images/da.png" alt="dansk" title="dansk" /></div><div style="float:left;padding:2px;" id="langForm-en"><img width="25" src="assets/images/en.png" alt="english" title="english" /></div><div style="float:left;padding:2px;" id="langForm-gr"><img width="25" src="assets/images/gr.png" alt="" title="" /></div></div><form id="orderForm">';
			str += data;
			
			str += '</form></div>';
				
			$('body').append(str);
			
			$("#dialog-orderform").dialog({
				width:800,
				height:600,
				modal: true,
				open: function(event, ui) { 
					
					$('#langForm-en').unbind();
					$('#langForm-da').unbind();
					$('#langForm-gr').unbind();
					
					// Rearrange buttons
					$('.ui-dialog-buttonset').attr('style', 'width:100%');
					btns = $('.ui-dialog-buttonpane button');
					$(btns[0]).attr('style','float:left');	
					$(btns[1]).attr('style','float:right');
					$(btns[2]).attr('style','float:right');
							
					// Attach click handlers for language
					$('#langForm-en').bind('click', function() {
						//console.log('en');
						$("#dialog-orderform").dialog('close', function() {
							$("#dialog-orderform").remove();
						});
						$LANGUAGE.lang = 'en';
						$BASKET.showOrderForm();
						
					});
					
					$('#langForm-da').bind('click', function() {
						//$LANGUAGE.translatePage('en');
						$("#dialog-orderform").dialog('close', function() {
							$("#dialog-orderform").remove();
						});
						//$("#dialog-orderform").remove();
						$LANGUAGE.lang = 'da';
						$BASKET.showOrderForm();
						
					});
					
					$('#langForm-gr').bind('click', function() {
						
						$("#dialog-orderform").dialog('close', function() {
							$("#dialog-orderform").remove();
						});
						//$("#dialog-orderform").remove();
						$LANGUAGE.lang = 'gr';
						$BASKET.showOrderForm();
					});
					
					$.getJSON("/index.php?id=54&action=getBasket", function(data){
							str = '<table id="basket_items" style="width:100%">';
							str += '<tr><td>'+$LANGUAGE.getTranslation($LANGUAGE.lang, 'foto_id')+'</td><td>'+$LANGUAGE.getTranslation($LANGUAGE.lang, 'amount')+'</td><td>'+$LANGUAGE.getTranslation($LANGUAGE.lang, 'item_price')+'</td><td></td><td align="right">'+$LANGUAGE.getTranslation($LANGUAGE.lang, 'total_price')+'</td></tr>';
						
						if (data != null) {
							for (var i = 0; i < data.length; i++) {
								str += '<tr class="items" id="item_'+data[i].bid+'"><td><div style="float:left"><a href="javascript:void(0);" title="delete" style="padding:0" onclick="$BASKET.removeFromOrderForm(\''+data[i].bid+'\');"><span class="ui-icon ui-icon-circle-close"></span></a></div><div style="float:left;"><a class="screenshot" title="'+data[i].bid+'" rel="http://arktiskebilleder.dk/image.php?bid='+data[i].bid+'&max_width=150&max_height=150">'+data[i].bid+'</a></div></td><td class="amount"><input type="text" size="2" value="1" id="item" name="item['+data[i].bid+']" /></td><td class="greybackground ppu"></td><td>Dkkr.</td><td align="right" class="greybackground ptpu"></td></tr>';
							}	
						}
						
						str += '<tr><td colspan="2">'+$LANGUAGE.getTranslation($LANGUAGE.lang, 'handling_charge')+'</td><td>75</td><td>Dkkr.</td><td align="right">75</td></tr>';
						str += '<tr class="total_price"><td colspan="3">'+$LANGUAGE.getTranslation($LANGUAGE.lang, 'final_price')+'</td><td>Dkkr.</td><td align="right" class="greybackground tp"></td></tr>';
							
						str += '</table>';
				
						$('#table_items').html(str);
						
						// Setup hovers
						if (data != null) {
							screenshotPreview(); 
						}
						
						// Setup events
						$("#basket_items input[type='text']").change( function() {
	  						$BASKET.calculateOrderForm();
						});
						
						$('#moms').change( function() {
	  						$BASKET.calculateOrderForm();
						});
						
						
						
					});
				},
				buttons: dialog_buttons,
				close: function(event, ui) { 
					$('#dialog-orderform').remove();
				}
			});
		});
		
	},
	
	showPricelist:function() { 
		
		$.get("/index.php?id=54&action=getPricelist&l="+$LANGUAGE.lang, function(data){
			var str = data;
				
			$('body').append(str);
			
			var dialog_button = {};
			
			dialog_button[$LANGUAGE.getTranslation($LANGUAGE.lang, 'close_price_list')] = function() {
				$( this ).dialog( "close" );	
				$BASKET.showOrderForm();
			}; 
			
			$("#dialog-pricelist").dialog({
				modal: true,
				width:800,
				height:600,
				buttons: dialog_button,
				close: function(event, ui) { 
					$('#dialog-pricelist').remove();
				}
			});	
		});
	},
	
	orderSentConfirmationDialog:function() {
		
		var str = '<div id="dialog-orderformConfirmation" title="'+$LANGUAGE.getTranslation($LANGUAGE.lang, 'order_receipt')+'" style="display:none;text-align:left"><p>'+$LANGUAGE.getTranslation($LANGUAGE.lang, 'order_receipt_text')+'</p></div>';
		
		
		
		$('body').append(str);
		
		$("#dialog-orderformConfirmation").dialog({
			modal: true,
			buttons: {
				'Luk':function() {
					$( this ).dialog( "close" );
					
				}
			},
			close: function(event, ui) { 
				$('#dialog-orderformConfirmation').remove();
			}
		});	
	},

	validateForm:function() {
		var error_str = '';
		var error = false;
		
		if ($('.chk_price input:checkbox:checked').val() == undefined) {
			error_str += $LANGUAGE.getTranslation($LANGUAGE.lang, 'error_specify_customer_group')+'<br />';
			//error_str += 'Angiv venligst kundegruppe.<br />';
			error = true;
		}
		
		var items = $('#basket_items tbody').children('.items');
		if (items.length == 0) {
			error_str += $LANGUAGE.getTranslation($LANGUAGE.lang, 'error_no_photos')+'<br />';
			//error_str += 'Der er ingen billeder i din bestilling.<br />';
			error = true;
		}
		else {
			// Check if amount is correct
			for (var i = 0; i < items.length; i++) {
				var check = false;
			
				if ($BASKET.isUnsignedInteger($(items[i]).children('.amount').children('input').val()) == false) {
					check = true;
				}
				
				if (check) {
					//error_str += 'Der mangler antal for et eller flere billeder<br />';
					error_str += $LANGUAGE.getTranslation($LANGUAGE.lang, 'error_photo_amont_not_specified')+'<br />';
					error = true;
				}	
			}
		}
		
		if ($('#name').val() == '') {
			//error_str += 'Angiv navn eller institution<br />';
			error_str += $LANGUAGE.getTranslation($LANGUAGE.lang, 'error_missing_name')+'<br />';
			error = true;
		}
		
		if ($('#email').val() == '') {
			//error_str += 'Angiv email<br />';
			error_str += $LANGUAGE.getTranslation($LANGUAGE.lang, 'error_missing_email')+'<br />';
			error = true;
		}
		else {
			if ($BASKET.IsValidEmail($('#email').val()) == false) {
				error_str += $LANGUAGE.getTranslation($LANGUAGE.lang, 'error_incorrect_email')+'<br />';
				//error_str += 'Den angivne email adresse er ikke korrekt.<br />';
				error = true;
			}
		}
		
		
		
		if ($('#telephone').val() == '') {
			error_str += $LANGUAGE.getTranslation($LANGUAGE.lang, 'error_missing_telephone')+'<br />';
			//error_str += 'Angiv telefon<br />';
			error = true;
		}
		
		if ($('#address').val() == '') {
			error_str += $LANGUAGE.getTranslation($LANGUAGE.lang, 'error_missing_address')+'<br />';
			//error_str += 'Angiv postadresse<br />';
			error = true;
		}
			
		if (error == true) {
			$('#form_errors').html(error_str);
			return false;
		}
		
		return true;
	},
	calculateOrderForm:function() {	
	
	  	var total_price = 0;
	  	var shipping_fee = 75;
	  	// Remove vat lines
	  	$('#basket_items tbody').children('.vat_lines').remove();
		   	
	 	var items = $('#basket_items tbody').children('.items');
	 	
	 	if ($('.chk_price input:checkbox:checked').val() != undefined && items.length > 0) {
		  	for (var i = 0; i < items.length; i++) {
		  		// set ppu
				$(items[i]).children('.ppu').html($('.chk_price input:checkbox:checked').val());
				
				// set price total pr. item
				var amount = $(items[i]).children('.amount').children('input').val();
				var price = $('#price_table input:checkbox:checked').val() * amount;
				$(items[i]).children('.ptpu').html(price);
				total_price = total_price + price;
				
			}
			$('#basket_items tbody .total_price').children('.tp').html(total_price+shipping_fee);
			
					
			// if VAT is checked
			if ($('#moms').attr('checked')) {
				var vat = (total_price+shipping_fee) * 0.25;
				
				var vat_str = '<tr class="vat_lines"><td colspan="5"><hr /></td></tr>'; 
				vat_str += '<tr class="vat_lines"><td colspan="3">'+$LANGUAGE.getTranslation($LANGUAGE.lang, 'info_vat')+'</td><td>Dkkr.</td><td align="right">'+vat+'</td></tr>';
				vat_str += '<tr class="vat_lines"><td colspan="3"><strong>'+$LANGUAGE.getTranslation($LANGUAGE.lang, 'info_total_price')+'</strong></td><td>Dkkr.</td><td align="right" class="greybackground" style="border-bottom: 3px double;">'+((total_price+shipping_fee)+vat)+'</td></tr>';
				$('#basket_items tbody').append(vat_str);
				//$('#basket_items tbody .total_price').children('.tp').attr('style', 'border-bottom: 1px');
			}
		}
	},

	isUnsignedInteger: function(s) {
	  return (s.toString().search(/^[0-9]+$/) == 0);
	},

	IsValidEmail:function(email) {
		var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
		return filter.test(email);
	}	
};
