/**
 * Filename: scripts.js
 *
 * @author Simon Jensen
 */

/***************************************************************************/
//GENERAL PURPOSE FUNCTIONS
/***************************************************************************/
function is_email(email)
{
	var apos = email.indexOf("@");
	var dotpos = email.lastIndexOf(".");
	
	if (apos<1||dotpos-apos<2) {
		return false;
	} else {
		return true;
	}
}

function slide_toggle(elem_id) {
	if($("#"+elem_id).is(':visible')) {
		$("#"+elem_id).slideUp();
	} else {
		$("#"+elem_id).slideDown();
	}
	return false;
}

/***************************************************************************/
//COOKIE FUNCTIONS
/***************************************************************************/
function createCookie(name,value,days,path)
{
	if(days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	if(path == "") {
		path = "/";
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path="+path;
}

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name)
{
	createCookie(name,"",-1,"");
}

function setLanguage(selector, redir, path)
{
	var option = getSelectedOption(selector);
	if(option != "")
	{
		createCookie("lang", option, 360, path);
	} else {
		createCookie("lang", "da_DK", 360, path);
	}
	location.href = redir;
}

/***************************************************************************/
//PRODUCT
/***************************************************************************/
$(document).ready(function() {
	
	// Create calendars
	$('#date_deadline').datepicker({
		yearRange: "-10:0",
		dateFormat: $.datepicker.ISO_8601,
		showOn: "both",
		buttonImage: "/gfx/icons/calendar.png",
		buttonImageOnly: true
	});
	
	// Create calendars
	$('#date_delivery').datepicker({
		yearRange: "-10:0",
		dateFormat: $.datepicker.ISO_8601,
		showOn: "both",
		buttonImage: "/gfx/icons/calendar.png",
		buttonImageOnly: true
	});
	
	// Create calendars
	$('#date_deadline_edit').datepicker({
		yearRange: "-10:0",
		dateFormat: $.datepicker.ISO_8601,
		showOn: "both",
		buttonImage: "/gfx/icons/calendar.png",
		buttonImageOnly: true
	});
	
	// Create calendars
	$('#date_delivery_edit').datepicker({
		yearRange: "-10:0",
		dateFormat: $.datepicker.ISO_8601,
		showOn: "both",
		buttonImage: "/gfx/icons/calendar.png",
		buttonImageOnly: true
	});
	
	$("#products").change(function () {
		$("#new_attributes").html('');
		
		var selected_product = "";
		$("#products option:selected").each(function () {
			selected_product = $(this).val();
		});
		if(selected_product != "") {
			$("#new_attributes").html('<center><img src="/gfx/loading.gif" alt="Loading..." /></center>');
			
			$.post("/actions/product.php", {
				todo: "get_product_info",
				product_id: selected_product
			},
			function(data) {
				if(data != "") {
					$(".box_470_gradient").fadeOut("fast", function() {
						$(".box_470_gradient").html(data).fadeIn("fast");
					});
				}
			});
			
			$.post("/actions/product.php", {
				todo: "get_attributes",
				product_id: selected_product
			},
			function(data) {
				$("#new_attributes").html('');
				var rand_id = Math.random();
				rand_id = rand_id.toString().substring(2)
				var html = '<div id="rand_'+rand_id+'" class="hidden">';
				$.each(data.keys, function(i, val) {
					html += '<table width="100%" cellspacing="0" cellpadding="2" border="0"><tr><td><p>'+val.key+'</p>';
					html += '<select name="attr['+val.key+']" class="w100">';
					html += '<option value="">- Vælg</option>';
					$.each(val.values, function(i_val, val_val) {
						html += '<option value="'+val_val.value+'">'+val_val.value+'</option>';
					});
					html += '</select>';
					html += '</td></tr></table>';
				});
				html += '</div>';
				$("#new_attributes").append(html);
				$("#rand_"+rand_id).slideDown("fast");
			},"json");
		}
	}).change();
	
	// Hijax the order form
	var order_options = {
		type: 'post',
		dataType: 'json',
		resetForm: false,
		beforeSubmit: function() {
			$("#create_errors").html('<a class="right" href="#" onclick="slide_toggle(\'create_errors\'); return false;">Luk</a>').css("display", "none");
			$("#order_submitter").attr("disabled", "true"); 
			$("#order_load_anim").show();
		},
		success: function(data) {
			$("#order_submitter").removeAttr("disabled"); 
			$("#order_load_anim").hide();
			if(data.err == 0) {
				location.href = ""+data.redir+"";
			} else {
				$.each(data.errors, function(i, val) {
					$("#create_errors").append(val.message+'<br />');
				});
				$("#create_errors").slideDown();
			}
			$.scrollTo('#container', 800);
		}
	};
	$('#order_form').ajaxForm(order_options);
	
	// Hijax the edit order form
	var edit_order_options = {
		type: 'post',
		dataType: 'json',
		resetForm: false,
		beforeSubmit: function() {
			$("#save_errors").html('<a class="right" href="#" onclick="slide_toggle(\'save_errors\'); return false;">Luk</a>').css("display", "none");
			$("#edit_order_submitter").attr("disabled", "true"); 
			$("#edit_order_load_anim").show();
		},
		success: function(data) {
			$("#edit_order_submitter").removeAttr("disabled"); 
			$("#edit_order_load_anim").hide();
			if(data.err == 0) {
				location.href = ""+data.redir+"";
			} else {
				$.each(data.errors, function(i, val) {
					$("#save_errors").append(val.message+'<br />');
				});
				$("#save_errors").slideDown();
			}
			$.scrollTo('#container', 800);
		}
	};
	$('#edit_order_form').ajaxForm(edit_order_options);
	
	// Prepare for post
	var settings_options = {
		type: 'post',
		dataType: 'json',
		resetForm: false,
		beforeSubmit: function() {
			$("#settings_response").html("").css("display", "none");
			$("#settings_submitter").attr("disabled", "true"); 
			$("#settings_load_anim").show();
		},
		success: function(data) {
			$("#settings_submitter").removeAttr("disabled"); 
			$("#settings_load_anim").hide();
			if(data.err == 0) {
				$("#settings_response").html('<div class="ui-corner-all message">'+data.message+'</div>').slideDown();
			} else {
				var error_html = '<div class="ui-corner-all ui-state-error">';
				$.each(data.errors, function(i, val) {
					error_html += val.message+'<br />';
				});
				error_html += '</div>';
				$("#settings_response").html(error_html).slideDown();
			}
			$.scrollTo('#container', 800);
		}
	};
	$('#settings_form').ajaxForm(settings_options);
	
});

/***************************************************************************/
//ORDER
/***************************************************************************/
function cancel_order(order_id, confirm_msg) {
	if(confirm(confirm_msg)) {
		$("#order_load_anim_"+order_id).show();
		$.post("/actions/order.php", {
			todo: "cancel",
			order_id: order_id
		},
		function(data) {
			$("#order_load_anim_"+order_id).hide();
			if(data.err == 0) {
				$("#order_"+order_id).fadeOut();
			} else {
				alert(data.message);
			}
		}, "json");
	}
}

$(document).ready(function() {
	
	// Prepare for post
	var comment_options = {
		type: 'post',
		dataType: 'json',
		resetForm: false,
		beforeSubmit: function() {
			$("#comment_errors").html('<a class="right" href="#" onclick="slide_toggle(\'comment_errors\'); return false;">Luk</a>').css("display", "none");
			$("#comment_submitter").attr("disabled", "true"); 
			$("#comment_load_anim").show();
		},
		success: function(data) {
			$("#comment_submitter").removeAttr("disabled"); 
			$("#comment_load_anim").hide();
			if(data.err == 0) {
				$("#comment_txt").val("");
				var html = '<div class="comment ui-widget-content ui-corner-all hidden" id="comment_'+data.comment_id+'">';
					html += '<div class="comment_meta">';
						html += '<img src="/gfx/icons/user.png" alt="" align="absmiddle" /> '+data.user_id+' &bull; <img src="/gfx/icons/time.png" alt="" align="absmiddle" /> '+data.created;
					html += '</div>';
					html += data.comment;
				html += '</div>';
				$("#new_comment").prepend(html);
				$("#comment_"+data.comment_id).slideDown();
				$("#no_comments").slideUp();
			} else {
				$.each(data.errors, function(i, val) {
					$("#comment_errors").append(val.message+'<br />');
				});
				$("#comment_errors").slideDown();
			}
		}
	};
	$('#comment_form').ajaxForm(comment_options);
	
});

/***************************************************************************/
//OFFER
/***************************************************************************/
function cancel_offer(offer_id, confirm_msg) {
	if(confirm(confirm_msg)) {
		$("#offer_load_anim_"+offer_id).show();
		$.post("/actions/offer.php", {
			todo: "cancel",
			offer_id: offer_id
		},
		function(data) {
			$("#offer_load_anim_"+offer_id).hide();
			if(data.err == 0) {
				$("#offer_"+offer_id).fadeOut(function() {
					$("#offer_"+offer_id).html('<div class="message ui-corner-all">'+data.message+'</div>').slideDown();
				});
			} else {
				alert(data.message);
			}
		}, "json");
	}
}

function accept_offer(offer_id, confirm_msg) {
	if(confirm(confirm_msg)) {
		$("#offer_load_anim_"+offer_id).show();
		$.post("/actions/offer.php", {
			todo: "accept",
			offer_id: offer_id
		},
		function(data) {
			$("#offer_load_anim_"+offer_id).hide();
			if(data.err == 0) {
				location.href = ''+data.redir+'';
			} else {
				alert(data.message);
			}
		}, "json");
	}
}

function decline_offer(offer_id, confirm_msg) {
	if(confirm(confirm_msg)) {
		$("#offer_load_anim_"+offer_id).show();
		$.post("/actions/offer.php", {
			todo: "decline",
			offer_id: offer_id
		},
		function(data) {
			$("#offer_load_anim_"+offer_id).hide();
			if(data.err == 0) {
				location.href = ''+data.redir+'';
			} else {
				alert(data.message);
			}
		}, "json");
	}
}

$(document).ready(function() {
	
	// Prepare for post
	var offer_options = {
		type: 'post',
		dataType: 'json',
		resetForm: false,
		beforeSubmit: function() {
			$("#create_offer_errors").html('<a class="right" href="#" onclick="slide_toggle(\'create_offer_errors\'); return false;">Luk</a>').css("display", "none");
			$("#offer_submitter").attr("disabled", "true"); 
			$("#offer_load_anim").show();
		},
		success: function(data) {
			$("#offer_load_anim").hide();
			if(data.err == 0) {
				location.href=''+data.redir+'';
			} else {
				$("#offer_submitter").removeAttr("disabled"); 
				$.each(data.errors, function(i, val) {
					$("#create_offer_errors").append(val.message+'<br />');
				});
				$("#create_offer_errors").slideDown();
			}
			$.scrollTo('#content', 800);
		}
	};
	$('#offer_form').ajaxForm(offer_options);
	
});

/***************************************************************************/
//SIGNUP
/***************************************************************************/
var timer = null;
var city = "";

function city_search(city) {
	$("#city_search_anim").show();
	$.post("/actions/address.php", {
		todo: "search",
		city: city
	},
	function(data) {
		$("#city_search_anim").hide();
		if(data.err == 0) {
			$.each(data.cities, function(i, val) {
				$("#city_search_result").append('<div style="padding:3px 0px; border-top: 1px solid #E6E6E6;"><a href="javascript:set_address(\''+val.zip+'\',\''+val.city+'\',\''+val.country+'\');">'+val.city+' ('+val.zip+', '+val.country+')</a></div>');
			});
		} else {
			$("#city_search_result").html(data.message);
		}
		$("#city_search_result").slideDown();
	}, "json");
}

function init_search(city) {
	timer = clearTimeout(timer);
	$("#city_search_result").slideUp().html("");
	if(city != "") {
		timer = setTimeout("city_search('"+city+"');", 500);
	}
}

function toggle_address(mode) {
	if(mode == "result") {
		$("#city_search").slideUp(function() {
			$("#city_result").slideDown();
		});
	} else {
		$("#city_result").slideUp(function() {
			$("#city_search").slideDown();
		});
	}
}

function set_address(zip, city, country) {
	$("#zip").val(zip);
	$("#city").val(city);
	$("#country").val(country);
	$("#city_search_result").hide().html("");
	toggle_address('result');
}

$(document).ready(function() {
	
	$("#city_search_input").keydown(function(e) {
		var q = $(this).val();
		init_search(q);
	});

	$("#city_search_input").keyup(function(e) {
		var q = $(this).val();
		init_search(q);
	});
	
	// Prepare for post
	var signup_options = {
		type: 'post',
		dataType: 'json',
		resetForm: false,
		beforeSubmit: function() {
			$("#create_user_errors").html('<a class="right" href="#" onclick="slide_toggle(\'create_user_errors\'); return false;">Luk</a>').css("display", "none");
			$("#create_user_messages").html('<a class="right" href="#" onclick="slide_toggle(\'create_user_messages\'); return false;">Luk</a>').css("display", "none");
			$("#user_create_submitter").attr("disabled", "true"); 
			$("#user_create_anim").show();
		},
		success: function(data) {
			$("#user_create_submitter").removeAttr("disabled"); 
			$("#user_create_anim").hide();
			if(data.err == 0) {
				location.href = ""+data.redir+"";
			} else {
				$.each(data.errors, function(i, val) {
					$("#create_user_errors").append(val.message+'<br />');
				});
				$("#create_user_errors").slideDown();
			}
			$.scrollTo('#container', 800);
		}
	};
	$('#signup_form').ajaxForm(signup_options);
	
	// Prepare for post
	var user_options = {
		type: 'post',
		dataType: 'json',
		resetForm: false,
		beforeSubmit: function() {
			$("#save_user_errors").html('<a class="right" href="#" onclick="slide_toggle(\'save_user_errors\'); return false;">Luk</a>').css("display", "none");
			$("#save_user_messages").html('<a class="right" href="#" onclick="slide_toggle(\'save_user_messages\'); return false;">Luk</a>').css("display", "none");
			$("#user_create_submitter").attr("disabled", "true"); 
			$("#user_create_anim").show();
		},
		success: function(data) {
			$("#user_create_submitter").removeAttr("disabled"); 
			$("#user_create_anim").hide();
			if(data.err == 0) {
				$.each(data.messages, function(i, val) {
					$("#save_user_messages").append(val.message+'<br />');
				});
				$("#save_user_messages").slideDown();
			} else {
				$.each(data.errors, function(i, val) {
					$("#save_user_errors").append(val.message+'<br />');
				});
				$("#save_user_errors").slideDown();
			}
			$.scrollTo('#container', 800);
		}
	};
	$('#user_form').ajaxForm(user_options);
	
});

/***************************************************************************/
//CONTACT
/***************************************************************************/
$(document).ready(function() {
	
	// Prepare for post
	var contact_options = {
		type: 'post',
		dataType: 'json',
		resetForm: false,
		beforeSubmit: function() {
			$("#contact_response").html("").css("display", "none");
			$("#contact_submitter").attr("disabled", "true"); 
			$("#contact_load_anim").show();
		},
		success: function(data) {
			$("#contact_submitter").removeAttr("disabled"); 
			$("#contact_load_anim").hide();
			if(data.err == 0) {
				$("#contact_form").slideUp(function() {
					$("#contact_response").html('<div class="ui-corner-all message">'+data.message+'</div>').slideDown();
				});
			} else {
				var error_html = '<div class="ui-corner-all ui-state-error">';
				$.each(data.errors, function(i, val) {
					error_html += val.message+'<br />';
				});
				error_html += '</div>';
				$("#contact_response").html(error_html).slideDown();
			}
			$.scrollTo('#container', 800);
		}
	};
	$('#contact_form').ajaxForm(contact_options);
	
});

/***************************************************************************/
//LOST PASSWORD
/***************************************************************************/
$(document).ready(function() {
	
	// Prepare for post
	var resend_options = {
		type: 'post',
		dataType: 'json',
		resetForm: false,
		beforeSubmit: function() {
			$("#resend_response").html("").css("display", "none");
			$("#resend_submitter").attr("disabled", "true"); 
			$("#resend_load_anim").show();
		},
		success: function(data) {
			$("#resend_submitter").removeAttr("disabled"); 
			$("#resend_load_anim").hide();
			if(data.err == 0) {
				$("#resend_form").slideUp(function() {
					$("#resend_response").html('<div class="ui-corner-all message">'+data.message+'</div>').slideDown();
				});
			} else {
				$("#resend_response").html('<div class="ui-corner-all ui-state-error">'+data.message+'</div>').slideDown();
			}
			$.scrollTo('#container', 800);
		}
	};
	$('#resend_form').ajaxForm(resend_options);
	
});

/***************************************************************************/
//OTHER
/***************************************************************************/
$(document).ready(function() {
	$("#signup_img").mouseover(function() {
		$(this).attr("src", "/gfx/btn_signup_active.png");
	}).mouseout(function(){
		$(this).attr("src", "/gfx/btn_signup.png");
	});
	
	var checkin = setInterval(function() {
		$.post("/actions/login.php", {
			todo: "ping"
		},
		function(data) {
			console.log(data.message);
		},"json");
	}, 60000);
	
	// Theme buttons
	$(".ui-button").hover(function(){ 
		$(this).addClass("ui-state-hover"); 
	}, function(){ 
		$(this).removeClass("ui-state-hover"); 
	}).mousedown(function() {
		$(this).addClass("ui-state-active"); 
	}).mouseup(function(){
		$(this).removeClass("ui-state-active");
	});
	
});