var index					= "http://www.tengo.com.au/"
var defaultRequestProcessor	= "request-processor.php";
var defaultRequestType		= "Ajax";
var defaultContainerType	= "div"
var defaultContentDivID		= "#content";
var hoverImage				= "";
var current					= 0;

String.prototype.trim = function(){return this.replace(/^\s+|\s+$/, '');};
if(location.href.indexOf("tengo.com.au")==-1){index = "http://localhost/tengo/www/";}
$(document).ready(function(){initialise();});
$(window).load(function(){initialiseGallery();});
$(window).unload(function(){if($("div#map").length>0){GUnload();}});

function initialise(){
	if($("div#home-panel").length>0){
		initialiseTextField("keywords-search", "enter keywords");
		initialiseTextField("item-name", "enter item name");
		flashError("submit-search","keywords-search","enter keywords");
		flashError("submit-sell","item-name","enter item name");
	};
	if($("div.product-listing-row").length>0){initialiseTooltip()};
	if($("div#map").length>0){loadMap();}
	$("a.mail-tengo").attr("href","mailto:info@tengo.com.au").html("info@tengo.com.au");
	$("div#sell-step-2, div#sell-step-3, div#sell-step-4").hide();
	$("div#sell-step-1 .form-heading img, div#sell-step-2 .form-heading img, div#sell-step-3 .form-heading img").hide();
	if(''==$("input#name").val()){$("input#name").focus();}
	else if(''==$("input#suburb").val()){$("input#suburb").focus();}
	else { $("input#price").focus(); }
	$("a[rel='external']").attr("target","_blank");
	$("div#search #keywords").focus();
	$("div#edit-details #name").focus();
	$("div#logo img").click(function(){document.location=index;});
	if($("ol.quick-links").length>0){$("ol.quick-links a").click(function(){$(this).next().toggle();});}
	if($("form#sell-item-form").length>0){
		initialiseFormValidation();
		initialiseAutocompleteSuburb();
	}
	if($("table#listing").length>0){
		$("table#listing tr").not(":first").hover(function(){$(this).addClass("hover");},function(){$(this).removeClass("hover");});
		$("table#listing tr").dblclick(function(){document.location = index + $(this).children(".column5").children("a.edit").attr("href");});
		$("table#listing tr:odd img:first").css("border","1px solid #999999");
	}
}

function flashError(submitID,textID, text){
	$("input#" + submitID).click(function(){
		if(text==$("input#" + textID).val()){
			attention("input#" + textID,200);
			return false;
		}
	});
}

function attention(selector,speed){$(selector).fadeOut(speed).fadeIn(speed).fadeOut(speed).fadeIn(speed).fadeOut(speed).fadeIn(speed, function(){$(this).val("").focus();});}

function tbRemove(){
	if(-1!=location.href.indexOf("details")){
		tb_remove();
	}else if((-1==location.href.indexOf("item/list"))){
		tb_show("Preview Item Post", "templates/snippets/preview-confirm.php?height=195&width=250&modal=true&itemID=" + $("div#item-id").text(), null);
	} else{
		tb_remove();
	}
}

function initialiseTextField(id, text){$("input#" + id).click(function(){if(text==$(this).val()) $(this).val("");}).blur(function(){if(''==$(this).val()) $(this).val(text);});}

function get(containerID,type,table,actionType,action,values){
	$(defaultContainerType+containerID).load(defaultRequestProcessor,{type:type,table:table,actionType:actionType,action:action,values:values});
}

function initialiseTooltip(){
	$("div.product-listing-item img").tooltip({
		bodyHandler: function(){
			return $("<img/>").attr("src", this.src.replace("small","medium"));
		},
		track: true,
		showURL: false,
		extraClass: "recent-items-tooltip",
		opacity: 0.00
	});
}

function listRecentItems(){
	$(defaultContainerType + "#recent-items-panel").load(defaultRequestProcessor,{type:defaultRequestType,table:"Item",actionType:"list",action:"ListRecent",values:""},function(){
		initialiseTooltip();
	});
}

function listItems(){$(defaultContainerType + defaultContentDivID).load(defaultRequestProcessor,{type:defaultRequestType,table:"Item",actionType:"list",action:"List",values:""});}

function addItem(){
	$(defaultContainerType + defaultContentDivID).load("templates/form/ItemForm.php", function(){
		$("input#username").focus();
		initialiseImages();
	});	
}

function retrieveItem(id){get(defaultContentDivID,defaultRequestType,"Item","retrieve","Retrieve",id);}

function updateItem(id){get(defaultContentDivID,defaultRequestType,"Item","update","PrepareUpdate",id);}

function prepareDeleteItem(id){
	if(location.href.indexOf("item/list")==-1){
		tb_show("Confirm Item Deletion", "templates/snippets/prepare-delete-item.php?height=130&width=390&modal=true&itemID=" + id, null);
	} else {
		tb_show("Confirm Item Deletion", "templates/snippets/prepare-delete-item-list.php?height=130&width=390&modal=true&itemID=" + id, null);
	}
}

function deleteItem(id){
	tb_remove();
	$.post(defaultRequestProcessor,{type:defaultRequestType,table:"Item",actionType:"delete",action:"Delete",values:id},function(){
		if(2==$("table#listing tr").length){
			var url = location.href;
			var page = location.href.charAt(location.href.length-1);
			if("1"==page){
				var emptyListHTML	 = "<div>\n";
				emptyListHTML		+= "\t <p>You do not currently have any items listed on tengo.com.au</p>\n";
				emptyListHTML		+= "\t <p>Click <a href=\"sell\">here</a> to add one!</p>\n";
				emptyListHTML		+= "</div>\n";
				$("table#listing").replaceWith(emptyListHTML);
			} else{
				document.location = url.replace(page,(page-1));
			}
		} else {
			$("tr#row"+id).fadeOut(function(){
				$("tr#row"+id).remove();
				$("body").oneTime(500,function(){
					$("table#listing tr").removeClass("alt");	
					$("table#listing tr:odd").addClass("alt");	
				});
			});
		}
	});
}

function deleteUnpostedItem(id){
	$.post(defaultRequestProcessor,{type:defaultRequestType,table:"Item",actionType:"delete",action:"Delete",values:id},function(){
		document.location = index;
	});
}

function gotoFormStep(type, step, idFocusField){
	var imagesAreValid = imagesValid();
	if($("form#sell-item-form").valid() & imagesAreValid){
		$("div#" + type + "-step-" + step).fadeIn(500, function(){
			$("input#" + idFocusField).focus();
		});
		$("div#" + type + "-step-" + (step-1) + " img").fadeIn(500);
		$("div#" + type + "-step-" + (step-1) + " p#continue").hide(500);
		$("div.back-to-account-top").fadeOut(1000);
		current = step-1;
		document.location = '#bottom';
		$("input[type='file'][value='']").not(":first").parent().remove();
	}else if(imagesAreValid){
		$("#sell-item-form").submit();
	}
}

function hasValidImageExtension(fileName){
	return ( (-1!=fileName.indexOf(".jpg")) || (-1!=fileName.indexOf(".jpeg")) || (-1!=fileName.indexOf(".gif")) );
}

function addImageField(){
	if( ( $("div.image").length + $("div.images").length ) < 9){
		imageText =  '\n<div class="image">\n';
		imageText += '	<input name="image[]" type="file" value="" />\n';
		imageText += '	<a href="javascript:;" onclick="removeImageField(this);"><img src="images/image-delete.gif" alt="Remove this image" /> Remove this image</a>\n';
		imageText += '	<br />\n';
		imageText += '</div>\n';
		$("div.image:last").after(imageText);
		$("div.image:last imput").click();
	} else {
		if(0==$("span.images-error").length){
			$("div#add-image a").after(' <span class="images-error error">You have reached the maximum image limit!</span>');
			$("span.images-error").fadeOut(2000, function(){$(this).remove();});
		}
	}
}

function removeImageField(object){
	$(object).parent().fadeOut();
	$(object).parent().remove();
}

function removeImage(itemID,imageNumber){
	$.post(defaultRequestProcessor,{type:defaultRequestType,table:"Image",actionType:"delete",action:"Delete",values:itemID + ',' + imageNumber});
	$("div#image" + imageNumber).remove();
	if( ( 9 > $("div.images").length ) && ( 1 > $("div.image").length ) ){
		addImageText =  '<div class="image">\n';
		addImageText += '	<input id="image" name="image[]" type="file" value="" />\n';
		addImageText += '<br />\n';
		addImageText += '</div>\n';
		addImageText += '<div id="add-image">\n';
		addImageText += '	<a href="javascript:addImageField();"><img src="images/image-add.gif" alt="Add another image" /> Add another image</a>\n';
		addImageText += '</div>\n';
		$("div#images").after(addImageText);
	}
}

function imagesValid(){
	var invalidImages = 0;
	$("input[type='file']").each(function(i){
		if($(this).val().length>0){
			if( !isFileValid($(this).val()) ){
				invalidImages++;
			}
		}
	});
	if(invalidImages>0){
		attention("ul.notes li:first",200);
		return false;
	}
	return true;
}

function isFileValid(data){
	data = data.replace(/^\s|\s$/g, "");
	if (data.match(/([^\/\\]+)\.(jpeg|jpg|gif)$/i) ){
		return true;
	}
	return false;
}

function initialiseFormValidation(){	
	$.validator.addMethod("pageRequired", function(value, element) {
		var $element = $(element)
		function match(index){return current == index && $(element).parents("#sell-step-" + (index + 1)).length;}
		if (match(0) || match(1)){return !this.optional(element);}
		return "dependency-mismatch";
	}, $.validator.messages.required)

	$("form#sell-item-form").validate({
		ignore: ".ignore",
		rules: {
			name: "required",
			suburb: "required",
			price: {pageRequired: true,number: true},
			description: "required",
			email: {pageRequired: true,email: true},
			phone: "number",
			seller: "pageRequired",
			password: {
				required: false,
				minlength: 5
			},
			confirmpassword: {equalTo: "#password"}
		},
		messages: {
			name: "Please enter the item name",
			suburb: "Please enter your suburb",
			price: {
				pageRequired: "Please enter the price for the item",
				number: "The price must be a valid numeric value (i.e. 199.95)"
			},
			description: "Please enter the item description",
			email: {
				pageRequired: "Please enter your email address",
				email: "Please enter a valid email"
			},
			phone: "The phone number must be a valid numeric value (i.e. 0439508332)",
			seller: "Please enter your name",
			password: "Please ensure your password is 5 or more characters long",
			confirmpassword: "The value of this field must match the value of the password field"
		}
	});

	$("form#edit-details-form").validate({
		ignore: ".ignore",
		rules: {
			name: "required",
			email: {required: true, email: true},
			password: {required:false, minlength:5},
			confirmpassword: {equalTo:"#password"},
			phone: "number"
		},
		messages: {
			name: "Please enter your name",
			email: {
				pageRequired: "Please enter your email address",
				email: "Please enter a valid email"
			},
			password: "Please ensure your password is 5 or more characters long",
			confirmpassword: "The value of this field must match the value of the password field",
			phone: "The phone number must be a valid numeric value (i.e. 0439508332)"
		}
	});

	$("form#contact-form").validate({
		ignore: ".ignore",
		rules: {
			name: "required",
			email: {required: true, email: true},
			comments: "required"
		},
		messages: {
			name: "Please enter your name",
			email: {
				required: "Please enter your email address",
				email: "Please enter a valid email"
			},
			comments: "Please enter your comments"
		}
	});

}

function postItem(post){
	$("span#duplicate-error").remove();
	$("span#duplicate").load("request-processor.php?type=Ajax&table=User&actionType=custom&action=EmailCheck", {values: $("input#email").val() + "," + $("input#password").val()},function(){			
		if($("input#password").length!=0){
			if(("1"==$("span#duplicate").text())){
				$("input#email").after('<span id="duplicate-error" class="error"> This email address is already in use</span>');
				return false;
			}		
		}
		if($("form#sell-item-form").valid() & imagesValid()){
			$("input#post").val(post);
			$("div.image input[value='']").parent().remove();
			tb_show('Processing Request', 'templates/snippets/processing-request.php?modal=true&amp;height=70&amp;width=200', null);
			$("body").oneTime(500,function(){
				$("form#sell-item-form").submit();
			});
		}
	});
}


function submitContact(){
	if($("form#contact-form").valid()){
		$("form#contact-form").submit();
	}
}

function initialiseGallery(){
	$("div#small-images img").not(".placeholder").css("cursor","pointer");
	$("div#small-images img").click(function(){
		$mediumImageSource = $(this).attr("src").replace('small','medium');
		if(($("div#medium-image img").attr("src")!=$mediumImageSource)&&($(this).attr("src")!='images/small-item-placeholder-2.jpg')){
			$("div#medium-image img").fadeOut(600, function(){
				if($mediumImageSource!='images/medium-item-placeholder-2.jpg') {
					$("div#medium-image img").attr("src",$mediumImageSource).fadeIn(600);
					hoverImage = $("div#medium-image img").attr("src");
				} else { $("div#medium-image img").attr("src",hoverImage).fadeIn(600); }
			});
		}
	});
}

function showFullSizeImage(){
	title = $("div#medium-image img").attr("title");
	path = $("div#medium-image img").attr("src").replace('medium','large');
	tb_show(title,path,null);
}

function prepareLogin(){
	tb_show('Tengo Login Terminal', 'templates/snippets/login.php?height=115&amp;width=295', null);
	setTimeout('focusEmail()',1000);
}

function focusEmail(){$("input#login-email").val(''); $("input#login-email").focus();}

function check(){
	$("div#login div.error").fadeOut(500);
	if(""==$("input#login-email").val().trim()){
		attention("input#login-email",200);
	}else if(""==$("input#login-password").val().trim()){
		attention("input#login-password",200);
	} else {
		$("div#valid").load(defaultRequestProcessor,{type:defaultRequestType,table:"User",actionType:"custom",action:"Login",values:$("input#login-email").val() + ',' + $("input#login-password").val()}, function(){
			$("a#login-button").hide(function(){
				$("img#ajax-loading").show();
			});
			if(1==$("div#valid").text()){
				$("div#login form").submit();
				return;
			} else {
				if($("div#login div.error").css('display','none')){
					$("div.error").text("Invalid Credentials. Try again!");
					$("div#login div.message").fadeOut(500, function(){
						$("div#login div.error").fadeIn(500);
					});
				}
			}
			$("input#login-email").oneTime(1000, function() {
				$("img#ajax-loading").hide(function(){
					$("a#login-button").show();
				});
			});
		});
	}
}

function emailPassword(){
	if(""==$("input#login-email").val().trim()){
		attention("input#login-email",200);
	} else {
		$("div#valid").load(defaultRequestProcessor,{type:defaultRequestType,table:"Password",actionType:"custom",action:"Email",values:$("input#login-email").val()}, function(){
			if("1"==$("div#valid").text()){
				$("div#login div.error").fadeOut(500, function(){
					$("div#login div.message").fadeIn(500);
				});
			} else {
				$("div#login div.message").fadeOut(500, function(){
					$("div.error").text("That email address is not found in our records");
				});
						$("div#login div.error").fadeIn(500);
			}
		});
	}
}

function removeAjaxLoading(){$("img#ajax-loading").hide(function(){$("a#login-button").show();});}

function updateUser(){
	$("span#duplicate-error").remove();
	$("span#duplicate").load("request-processor.php?type=Ajax&table=User&actionType=custom&action=EmailCheck", {values: $("input#email").val() + "," + $("input#password").val()},function(){			
		if(("1"==$("span#duplicate").text())){
			$("input#email").after('<span id="duplicate-error" class="error"> This email address is already in use</span>');
			return false;
		}		
		if($("form#edit-details-form").valid()){
			var values = $("input#name").val() + ',' + $("input#email").val() + ',' + $("input#password").val() + ',' + $("input#phone").val() + ',' + $("input#address").val();
			$.post(defaultRequestProcessor,{type:defaultRequestType,table:"User",actionType:"update",action:"Update",values:values},function(){
				$("div#edit-details p").fadeOut(function(){
					$(this).html("<div class=\"message\">Details updated successfully.</div>");
					$("input#password").val("");
					$("input#confirmpassword").val("");
					$(this).fadeIn(1000).fadeOut(2000,function(){
						$(this).html("<a class=\"next\" href=\"javascript:updateUser();\">Save Changes <img src=\"images/continue.gif\" alt=\"Save Changes\" title=\"Save Changes\"/></a>");	
						$(this).fadeIn(1000);
					});
				});
			});
		}
	});
}

function submitContact(){
	if($("form#contact-form").valid()){
		var values = $("input#name").val() + ',' + $("input#email").val() + ',' + $("textarea#comments").val();
		$.post(defaultRequestProcessor,{type:defaultRequestType,table:"Contact",actionType:"custom",action:"Email",values:values},function(){
			$("p.submit").fadeOut(500,function(){
				$("input#name").val("");
				$("input#email").val("");
				$("textarea#comments").val("");			
				$("p.submit").after('<p class="message" style="display:none;">Your message has been sent. Thanks for contacting us! =]</p>');
				$("p.message").fadeIn(500,function(){
					$("p.message").fadeOut(4000,function(){
						$("p.submit").fadeIn(1000);
						$(this).remove();
					});				
				});
			});
		});
	}
}

function prepareRemoveAccount(){tb_show(null, 'templates/snippets/remove-account-confirm.php?height=130&width=480&amp;modal=true', null);}

function deleteAccount(){
	$.post(defaultRequestProcessor,{type:defaultRequestType,table:"Account",actionType:"delete",action:"Delete",values:""},function(){
		document.location=index;
	});
}

function toggleMap(){
	if("none"==$("div#map-container").css("display")){
		$("div#map-container").slideDown(1000,function(){$(window).scrollTop(400)});
		loadMap();
	} else {
		$("div#map-container").slideUp(1000,function(){$(window).scrollTop(0)});
	}
}

function loadMap(){
	if (GBrowserIsCompatible()){
		var map = new GMap2(document.getElementById("map"));
		map.addControl(new GMapTypeControl());
		map.addControl(new GSmallMapControl());
		var geocoder = new GClientGeocoder();
		var address = $("span#street-address").text() + ', ' + $("span#suburb").text() + ', ' + $("span#state").text();
		geocoder.getLatLng(address,function(point){
			if (!point) {
				$("div#map-container").hide();
			} else {
				map.setCenter(point, 13);
				var marker = new GMarker(point);
				map.addOverlay(marker);
				marker.openInfoWindowHtml('<h4>' + $("span#item-name").text() + '</h4>');
				$("span#street-address").wrap('<a href="javascript:toggleMap();" class="map-link"></a>');
			}
		});
	}
}

function initialiseAutocompleteSuburb(){
	$("input#suburb").autocomplete("request-processor.php?type=Ajax&table=Locality&actionType=list&action=List&values=" + $("select#state").val(), {
		minchars: 5,
		width: 142,
		max: 4,
		highlight: false,
		scroll: true,
		scrollHeight: 300,
		matchContains: true,
		formatItem: function(data, i, n, value) {
			return value.split(",")[0];
		},
		formatResult: function(data, value) {
			return value.split(",")[0];
		}
	});
}