/* function lib*/

function set_init() {
	
	$('#currency_combo').change(function() {
			
		// top.window.location = "/index.html?currency="+$('#currency_combo').val();
		
		top.window.location = top.window.location.href + "?currency="+$('#currency_combo').val();
	});
	
	$("select#currency_combo option").each(function() { 
		
		this.selected = (this.value == currency_id); 
	});
	
	//get_product_prices();
	
}

function get_product_prices() {
	
	var price= new Number();
	var pid = 0;
	
	$.get("/xml/get.php?id=get_product_price", function(xmldata){
		
		$.result_data = new Array();

		$("row", xmldata).children().each(function() {

			var tag_name = this.tagName;
			var txt = $(this).text();
			
			if (tag_name == "product_id") {
				
				pid = txt;
				
				$.result_data[pid]  = new Array();
			}
			
			$.result_data[pid][tag_name] = txt;
			
			if (tag_name == "big_image") {

				price = new Number(($.result_data[pid]["price_EURO"]/100) * currency_rate);
				
				$('#price_'+pid).html(price.toFixed(2)+" "+currency);
				
				$('#product_table').append(
					'<tr>'
					+'<td class="product_name" style=\'width:33%\'>'+$.result_data[pid]["description_line"]+'</span></td>'
			          +'<td class="product_price" style=\'width:17%;text-align:right\'>'+price.toFixed(2)+'&nbsp;'+currency+'&nbsp;&nbsp;</td>'
			          +'<td><img src=\''+$.result_data[pid]["small_image"]+'\'></td>'
			          +'<td class="product_action" style=\'width:50%\'><a href=\'javascript:add_product('+pid+')\'>Add '+$.result_data[pid]["description_line"]+'</a></td>'
					+'</tr>'
				);
			}
		});	
	});
}

function add_product(product_id) {
	
	// alert('add');
	
	$.result_data = new Array();

	$.get("/xml/get.php?id=add_product&session="+$.session_data['session_id']+"&product_id="+product_id, function(xmldata){

		// alert('success');
		
		$("result", xmldata).children().each(function() {

			var tag_name = this.tagName;
			var txt = $(this).text();
			$.result_data[tag_name] = txt;
		});	

		if ($.result_data["affected_rows"] != 1) {

			alert("Failed to add product");
			return;
		}
		top.window.location = "/cart.php";
		
		print_cart_lines();
	});
}

function remove_line(line_id) {

	$.result_data = new Array();

	$.get("/xml/get.php?id=remove_product&session="+$.session_data['session_id']+"&line_id="+line_id, function(xmldata){

		$("result", xmldata).children().each(function() {

			var tag_name = this.tagName;
			var txt = $(this).text();
			$.result_data[tag_name] = txt;
		});	

		if ($.result_data["affected_rows"] != 1) {

			alert("Failed to remove product");
			return;
		}
		print_cart_lines();
	});
}

function print_cart_lines(display_type) {

	$.post("/xml/get.php?id=cart&session="+$.session_data['session_id'], function(xmldata){
		
		// alert('cart load success');
		
		xdata = new Array();
		var cnt = 0;
		var debug_str = '';
		var remove_line = '';
		var cart_remove_line = '';
		var str = '';
		var total = new Number(0);
		var odd_even = '';
		var amount_seeds,quantity,display_quantity;
		var amount_items = new Number(0);

		$("row", xmldata).children().each(function() {

			var tag_name = this.tagName;
			var txt = $(this).text();

			if (tag_name == 'orderline_id') {

				cnt++;
			}

			if (typeof(xdata[cnt]) == 'undefined') {
				xdata[cnt] = new Array();
			}
			xdata[cnt][tag_name] = new String(txt);
		});

		if (cnt == 0) {
			var total_html = (total.toFixed(2))+'&nbsp;'+currency;

			$('#cart_table').html('<tr class="even"><td class="product_name" colspan="5">No products in cart.</td></tr>');
			$('#cart_table_side').html('<tr class="even"><td class="product_name" colspan="5">No products in cart.</td></tr>');
			
			$('#cart_table_total').html('Total : '+total_html);
			
			$('#cart_table_side_subtotal').html('&nbsp;'+total_html);
			$('#cart_table_subtotal').html('&nbsp;'+total_html);
			
			$('#cart_table_shipprice').html('&nbsp;'+total_html);

			return;
		}
		else {
			$('#cart_table').html('');
			$('#cart_table_side').html('');
		}

		cnt=0;

		for (x in xdata) {

			cnt++;
			amount_seeds = 10 * (new Number(xdata[x]['amount']));
			amount_items = amount_items + new Number(xdata[x]['amount']);
			remove_line = '<span class="action_remove" l_id="'+xdata[x]['orderline_id']+'"></span>';
			cart_remove_line = '<a href="javascript:remove_line('+xdata[x]['orderline_id']+');"  name="quantity_package"><img src="http://www.amsterdammarijuanaseedbank.com/images/icons/remove_item.png"></a>';

			if (display_type == 1) {

				cart_remove_line = "";
			}

			str = new String(xdata[x]['description_line']);
			total += new Number(xdata[x]['lineprice']);
			quantity = '<td class="product_quantity">Qty '+xdata[x]['amount']+'</td>';

			if (str.match(/free/gi) != null){ // && str.match(/seed/gi)) {

				remove_line = '&nbsp;';
				cart_remove_line = '&nbsp;';
			}

			if (xdata[x]['lineprice'] == '0.00') {

				amount_seeds = 20;
				quantity = '<td class="product_quantity">&nbsp;</td>';
			}

			var line_price = new Number(xdata[x]['lineprice']*currency_rate);
			var line_price_html = '&nbsp;'+currency_sign+'&nbsp;'+(line_price.toFixed(2))+'&nbsp;'+currency;

			if (xdata[x]['lineprice'] == '0.00') {

				odd_even = 'odd';

				if ((cnt%2) == 0) {
					odd_even = 'even';
				}

				$('#cart_table').append(
					'<tr class="'+odd_even+'">'
					+'<td class="product_name"><span class="free_seeds_as_cart_line">'+xdata[x]['description_line']+'</span></td>'
			          +'<td class="product_amount">'+amount_seeds+'  <span txt="TXT_126">Seeds</span></td>'
			          +quantity
			          +'<td class="product_price">'+line_price_html+'</td>'
			          +'<td class="product_action">'+cart_remove_line+'</td>'
					+'</tr>'
				);
				
				$('#cart_table_side').append(
					'<tr class="'+odd_even+'">'
					+'<td style="font-size:11px;">'+xdata[x]['description_line']+'</td>'
			          +'<td style="text-align:right; font-size:11px;">'+line_price_html+'</td>'
			          +'</tr>'
				); 
			}

			else {
				odd_even = 'odd';

				if ((cnt%2) == 0) {

					odd_even = 'even';
				}	

				$('#cart_table').append(
					'<tr class="'+odd_even+'">'
					// +'<td class="product_name"><a class="shopping_cart_product_link" href="/'+xdata[x]['description_line']+'.php">'+xdata[x]['description_line']+'</a></td>'
					+'<td class="product_name">'+xdata[x]['description_line']+'</td>'
			          +'<td class="product_amount">'+amount_seeds+' <span txt="TXT_126">Seeds</span></td>'
			          +quantity
			          +'<td class="product_price">'+line_price_html+'</td>'
			          +'<td class="product_action">'+cart_remove_line+'</td>'
					+'</tr>'
				);
				
				$('#cart_table_side').append(
					'<tr class="'+odd_even+'">'
					+'<td style="font-size:11px;">'+xdata[x]['description_line']+'</td>'
			          +'<td style="text-align:right; font-size:11px;">'+line_price_html+'</td>'
			          +'<td class="product_action">'+cart_remove_line+'</td>'
			          +'</tr>'
				); 
			}
		}

		var total_price = new Number(total*currency_rate);
		var total_price_html = '&nbsp;'+currency_sign+'&nbsp;'+(total_price.toFixed(2))+'&nbsp;'+currency;

		$('#cart_table_subtotal').html('&nbsp;'+total_price_html);
		$('#cart_table_side_subtotal').html('&nbsp;'+total_price_html);
		
		var ship_price = new Number((14+amount_items)*currency_rate);
		var ship_price_html = '&nbsp;'+currency_sign+'&nbsp;'+(ship_price.toFixed(2))+'&nbsp;'+currency;

		$('#cart_table_shipprice').html('&nbsp;'+ship_price_html);

		total = total_price + ship_price;

		var total_price_html = '&nbsp;'+currency_sign+'&nbsp;'+(total.toFixed(2))+'&nbsp;'+currency;

		$('#cart_table_total').html('Total : '+total_price_html);

		$('.action_remove').click(function() {
			var line = $(this).attr('l_id');
			top.remove_line(line);
		});
	});	
}

function form_error_handler(my_form, required, email, errornotice, emptyerror, emailerror) {

	

	$("#"+my_form).submit(function(){

		//alert('submit');

		//Validate required fields

		for (i=0;i<required.length;i++) {

			var input = $('#'+required[i]);

			if ((input.val() == "") || (input.val() == emptyerror)) {

				input.addClass("needsfilled");

				input.val(emptyerror);

				errornotice.fadeIn(750);

			} else {

				input.removeClass("needsfilled");

			}

		}

		if (email != 0) {

			// Validate the e-mail.

			if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {

				email.addClass("needsfilled");

				email.val(emailerror);

			}

		}	

		//if any inputs on the page have the class 'needsfilled' the form will not submit

		if ($(":input").hasClass("needsfilled")) {

			

			return false;

		} else {

			$('#'+my_form).trigger('form_ok');

			errornotice.hide();

			return false;

		}

	});

	

	// Clears any fields in the form when the user clicks on them

	$(":input").focus(function(){

		if ($(this).hasClass("needsfilled") ) {

			$(this).val("");

			$(this).removeClass("needsfilled");

		}

	});

}

function check_order_status() {
	
	$.ajax({
		type: "GET",
		url: "xml/get.php?id=order&session="+$.session_data['session_id'],
		dataType: "xml",
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			// error message
			return;
		},
		success: function(xml, textStatus) {
			
			var o_status = new Number($("row", xml).find("status").text());
			var o_shipprice = new Number($("row", xml).find("shipprice").text());
	
			if (ordered_items > 0) {
				
				if (o_shipprice == 16.00) {
					
					o_shipprice = 14.00;
				}
				else {
					ordered_items = 0;
				}
				
				var ship_price = new Number((o_shipprice+ordered_items)*currency_rate);
				var ship_price_html = (ship_price.toFixed(2))+'&nbsp;'+currency;
				
				var mail_type_text = 'Priority mail';
				
				if ((o_shipprice * 100) > 2000) {
					
					var mail_type_text = 'Registered with track and trace';
				
				}
				
				$('#cart_table_items').html('&nbsp;('+mail_type_text+')');
				$('#review_table_items').html('&nbsp;('+mail_type_text+')');
				
				$('#cart_table_shipprice').html('&nbsp;'+ship_price_html);
				$('#review_table_shipprice').html('&nbsp;'+ship_price_html);
				
				var subtotal_price = new Number(sub_total*currency_rate);
				//var subtotal_price_html = (subtotal_price.toFixed(2))+'&nbsp;'+currency;
				//$('#cart_table_subtotal').html('&nbsp;'+subtotal_price_html);
				var totalPrice = subtotal_price + ship_price;
				var total_price_html = (totalPrice.toFixed(2))+'&nbsp;'+currency;
				$('#cart_table_total').html('Total : '+total_price_html);
			}
	
			
		}
	});
	
}


$('#contact_form').submit(function() {
		
		$.get("xml/post.php?file_id=1&session="+$.session_data['session_id']+"&"+$(this).serialize(), function(xmldata){
			
			$.result_data = new Array();
			
			$("result", xmldata).children().each(function() {
			
				var tag_name = this.tagName;
				var txt = $(this).text();
				
				$.result_data[tag_name] = txt;
				
			});
			
			if (!$.result_data["inserted_id"]) {
				
				// $(this).find("description");
				// debug_object($(this).find("description").tagName);
				alert($("error", xmldata).find("description").text());
				return;
			}
			
			alert('Contact form received');
			
		});
		// alert($(this).serialize());
		return false;
	});


