//Main template functions

$(function() {
	
	$(window).scroll(function(){
		p = $("#msgPanel").css('position');
		changed = false;
		st = $(window).scrollTop();
		
		if(st > 230) {
			if(p != 'fixed') {
				changed = true;
				$("#msgPanel").css({position:"fixed",left:"auto",top:"0px",marginLeft:"220px"});
			}
		} else {
			if(p != 'absolute') {
				changed = true;
				$("#msgPanel").css({position:"absolute",left:"220px",top:"230px",marginLeft:"0px"});
			}	
		}
		
		//ie7 needs hides the products without this:
		if(changed && $.browser.msie && $.browser.version < 8) {
			$('#pHolder').html($('#pHolder').html());
		}
	});
	
	//set default values
	var stype = "<?=$search;?>";
	$('#ddSearchOptions').val('<?=$search;?>');
	$('#txtKeyword').val('')
	$('#txtRLower').val('');
	$('#txtRUpper').val('');
	
	switch(stype) {
		case "keyword":
			$('#sKeyword').show();
			$('#sRange').hide();
		break;
		
		case "range":
			$('#sKeyword').hide();
			$('#sRange').show();
		break;
	}
	

    $('#txtKeyword,#txtRLower,#txtRUpper').keydown(function(e){
        if (e.keyCode == 13) {
            $('#frmSearch').submit();
            return false;
        }
    });

	
	//LHS menu click function					   
	$(".tLeftMenu li a").bind("click",function() {
		if($(this).parent().find("a").size() > 1 ) { //if parent <li> has more than 1 <a> tag in it
			$(this).parent().parent().find("li ul:visible").not($(this).parent().find("ul:first")).slideToggle();
			$(this).parent().find("ul:first").slideToggle(500);
			return false;
		}
	});
	
	//login form submit function
	$('#frmLogin').submit(function() {
		
		var username = $('#txtEmail').val();
		var password = $('#txtPassword').val();
				
		if(username != "" && password != "") {
			
			if(validateEmail(username)) {
				return true;
			} else {
				showMsg('Please enter a valid email address!','error');
			}
			
		} else if(username == "") {
			showMsg('Please enter a username!','error');
		} else if(password == "") {
			showMsg('Please enter a password!','error');
		}
		
		return false;
	});
	
	$('#btnLogout').click(function() {
		$('#frmLogout').submit();
		return false;
	});
	
	//change function for search options drop down	
	$('#ddSearchOptions').change(function() {
		stype = $('#ddSearchOptions').val();
		
		switch(stype) {
			case "keyword":
				$('#sKeyword').show();
				$('#sRange').hide();
			break;
			
			case "range":
				$('#sKeyword').hide();
				$('#sRange').show();
			break;
		}
	});
	
	//validate member
	$("input[name='member_submit']").click(function() {
		if($('#member_number').val() != '') {
			$.ajax({
				type: "POST",
				url: "/functions/member_check.php",
				data: "id="+$('#member_number').val(),
				success: function(response) {
					if(response == 'Y') {
						window.location="/checkout/summary";
					} else {
						$('.discount_msg').html(response);
					}
				}
			});
		} else {
			//alert("Please enter your membership number!");
			$('.discount_msg').html('<span style="color:red;">Please enter a number!');
		}
	});

	//search form submit function
	$('#frmSearch').submit(function() {
		
		var searchval = "";
		stype = $('#ddSearchOptions').val();
		
		switch(stype) {
			case "keyword":
				searchval = $('#txtKeyword').val();
				var pattern = /^[a-zA-Z0-9 ]+$/;
				
				if(searchval.match(pattern)) {
					//submit form
				} else {
					showMsg('Please enter a valid keyword!','error');
					return false;
				}
			break;
			
			case "range":
				var rLower = $('#txtRLower').val();
				var rUpper = $('#txtRUpper').val();
				
				//allow up to 6 digits, which can have an optional decimal point with 2 digits on the end
				var pattern = /^\$?(\d{1,3},?(\d{3},?)*\d{3}(\.\d{0,2})?|\d{1,3}(\.\d{0,2})?|\.\d{1,2}?)$/
				
				if(rLower.match(pattern) && rUpper.match(pattern)) {
					if(parseInt(rUpper) <= parseInt(rLower)) {
						showMsg('Upper value must be higher than lower value!','error');
						return false;
					}
				} else {
					showMsg('Please enter valid numbers!','error');
					return false;
				}
								
				/*if(rUpper == '' && rLower != '') {
					if(rLower.match(pattern)) {
						rUpper = "max";
						//submit form
					}
				} else {
					if(rLower.match(pattern) && rUpper.match(pattern)) {
						if(rUpper > rLower) {
							//submit form
						} else {
							$('#alertMsg').html('Upper value must be higher than lower value!');
							$('#alertPanel').show();
							return false;
						}
					} else {
						$('#alertMsg').html('Please enter valid numbers!');
						$('#alertPanel').show();
						return false;
					}
				}*/
					
			break;
		}
		
	});
	
	//close alert panel
	$('#btnMsgClose').click(function() {
		$('#msgPanel').fadeOut();
		return false;
	});
	
	//validate email function
	function validateEmail(email) {
		if(email.length <= 0) {
		  return false;
		}
		var splitted = email.match("^(.+)@(.+)$");
		if(splitted == null) return false;
		if(splitted[1] != null ) {
			var regexp_user=/^\"?[\w-_\.]*\"?$/;
			if(splitted[1].match(regexp_user) == null) return false;
		}
		if(splitted[2] != null) {
			var regexp_domain=/^[\w-\.]*\.[A-Za-z]{2,4}$/;
			if(splitted[2].match(regexp_domain) == null) {
				var regexp_ip =/^\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]$/;
				if(splitted[2].match(regexp_ip) == null) return false;
			}
			return true;
		}
		return false;
	}
	
});

var t;	//initialise timeout variable

//show the specified message (msg = message text string, type = success or error)
function showMsg(msg,type) {
	
	
	clearTimeout(t);
	
	if(type == "success") {
		$('#msgPanel').css({backgroundColor:"#D4F8BC"});	//apply green css
	} else if(type == "error") {
		$('#msgPanel').css({backgroundColor:"#F5E8E8"});	//apply red css
	}
	
	$('#msgText').html('<div id="msg'+type+'">'+msg+'</div>');
	$('#msgPanel').fadeIn();
	t = setTimeout(fadePanel, 6000);	//set fade out time
	
}

//called via setTimeout to fade panel after specified amount of time
function fadePanel() {
	$("#msgPanel").fadeOut();
}

//add product to shopping cart
function addCart(id) {
	
	$.ajax({
		type: 	"POST",
		url: 	"/functions/cart_action.php",
		data:	"prod_id="+id+"&action=add",
		success: function(response) {			
			$('#tCartDetails').html(response);	//update cart info display
			showMsg('Product added to cart!','success');
		}
	});
}

//add product to shopping cart from wishlist
function addCartWishlist(id,a) {
	
	$.ajax({
		type: 	"POST",
		url: 	"/functions/cart_action.php",
		data:	"prod_id="+id+"&action=add",
		success: function(response) {
			$('#tCartDetails').html(response);	//update cart info display			
			showMsg('Product added to cart!','success');
			$(a).parent().parent().find('td').css({"color":"#0c831a"});
			$(a).parent().parent().find('td a').css({"color":"#0c831a"});
			//$(a).find('img').attr("src",'/templates/main/images/buttons/wishlist_added.jpg');
			$(a).parent().html('<img src="/templates/main/images/buttons/wishlist_added.jpg" alt="Added to Cart" border="0" /></a>');
		}
	});
}

//add product to wishlist
function addWishlist(id) {
	
	$.ajax({
		type: 	"POST",
		url: 	"/functions/wishlist_action.php",
		data:	"prod_id="+id+"&action=add",
		success: function(response) {	
			
			switch(response) {
				
				case "added":
					showMsg('Product added to your Wishlist!','success');
				break;
				
				case "exists":
					showMsg('Selected product is already in your Wishlist!!','error');
				break;
				
				case "login":
					showMsg('You must be logged in to add to your Wishlist!','error');
				break;
				
			}
			
		}
	});
}

//remove product from Wishlist
function removeWishlist(id,a) {
	
	var row = $(a).parent().parent(); //target containing <tr>
	
	if(confirm("Are you sure you want to remove this product from your Wishlist?")) {
	
		$.ajax({
			type: "POST",
			url: "/functions/wishlist_action.php",
			data: "prod_id=" + id + "&action=remove",
			success: function(response) {
			
				//remove row
				row.fadeOut("slow", function() {
					if($(this).parent().find('tr').size() <= 2) {
						$('.wishlist').find('tr:eq(1)').html('<td colspan="4">You have no products in your Wishlist</td>');
					}
					else {
						$(this).remove();
					}
				});
				
			}
		});
		
	}
}

//display larger product image
function loadImage(img) {
	
	$('#large').attr("src",'/library/image/'+img+'.jpg');
	
}
