/*
	@name: AAE
	@author: Simon Coulton
	@version: 1.0
*/


var AaE = {
	debug: false,
	log: function() {
		var a=arguments,i;
		for (i=0; i<a.length; i++) {
			if ($.browser.mozilla) console.debug(a[i]);
		}
	},
	xy: function(obj) {
		var curleft = curtop = 0;
		if (obj.offsetParent) {
			curleft = obj.offsetLeft
			curtop = obj.offsetTop
			while (obj = obj.offsetParent) {
				curleft += obj.offsetLeft
				curtop += obj.offsetTop
			}
		}
		return [curleft,curtop];
	},
	init: function() {
		var searchField = $(".home .searchfield");
		if (searchField) {
			searchField.keydown(function(e) {
				var kk = e.keyCode?e.keyCode:e.which;
				if ((kk == 13) && (searchField.val())) {
					submitSearch();
				}
			});
		}
		var tracktracefield = $("#inqnum");
		if (tracktracefield) {
			tracktracefield.keydown(function(e) {
				var kk = e.keyCode?e.keyCode:e.which;
				if (kk == 13) {
					trackTraceSearch($("#Search")[0]);
					return false;
				}
			});
		}
		var bushnetuser = $("#txtUserID");
		var bushnetpass = $("#txtPassword");
		if ((bushnetuser) && (bushnetpass)) {
			bushnetuser.keydown(function(e) { var kk = e.keyCode?e.keyCode:e.which;	if (kk == 13) { bushNETLogin();	} });
			bushnetpass.keydown(function(e) { var kk = e.keyCode?e.keyCode:e.which;	if (kk == 13) { bushNETLogin();	} });
		}
		//$(".toggle").each(function() { var nav = $(this).html().toString(); var start = nav.indexOf("src="); nav = nav.substr(start); var end = nav.indexOf("\"", 8); nav = nav.substr(0, (end?end:nav.length)); nav = "<img "+nav+"\" border=\"0\" />"; $(this).html(nav); });
$(".toggle").each(function() { 
var nav = $(this).html().toString(); 
var start = nav.indexOf("src="); 
nav = nav.substr(start); 
var end = nav.indexOf("\"", 8); 
nav = nav.substr(0, (end?end:nav.length)); 
nav = nav.substr(nav.indexOf("/portal"));
$(this).html("<img src=\""+nav+"\" border=\"0\" alt=\"\" />"); 
}); 
		var cookie = AaE.util.Cookie.read("style");
		var title = cookie ? cookie : AaE.util.StyleSwitcher.getPreferred();
		AaE.util.StyleSwitcher.setActive(title);
		$("input:checkbox").css("border","0");
		var flashVars = { appRoot: "portaldata/1/resources/0_homepage/flash/" };
		var params = { wmode: "transparent", scale: "noscale" };
		var attributes = {};
		swfobject.embedSWF("portaldata/1/resources/0_homepage/flash/weather.swf","weatherpane",636,100,"9.0.0",null,flashVars,params,attributes);
		$(".fr").each(function(i,el) {
			var el = $(el), css = el.attr('class'), size = css.split(" ")[1], wh = size.split("x"), id = el.attr("id"), src = el.attr("src"), alt = el.attr('alt'), align = el.attr('align');
			if (id) {
				var flashVars = { image: src, alt: alt };
				var params = { wmode: 'transparent' };
				var attributes = {};
				swfobject.embedSWF("portaldata/1/resources/flash/"+size+".swf",id,wh[0],wh[1],"9.0.0",null,flashVars,params,attributes);
			}
		});
		$("*[alt*='aae.lb']").click(function(e) {
			new AaE.util.Lightbox(this);
		});
		/*if (AaE.debug) {
			$(".ACTION_REQUIRED").each(function(i,n) {
				var types = {
					A: "Link",
					IMG: "Image"
				};
				var obj = $(n);
				var html = "<div><h3 class=\"error\">THE FOLLOWING ITEMS ARE REQUIRED ON THIS PAGE (red borders)</h3>";
				html += types[n.tagName] + ": " + (obj.text()?obj.text():obj.attr('alt'));
				html += "<br /><br /><br /></div>";
				$(".contentpane").html($(".contentpane").html() + html);
				obj.css("border","1px solid red");
			});
		}*/
		var freightMasterRegistration = $(".FreightMasterSubmit");
		
		freightMasterRegistration.click(function(e) {
			var Errors = [];
			var Fields = ["Company Name", "Billing Account Number", "Contact Name", "Contact Telephone", "Contact Mobile", "Contact Facsimile", "Contact Email", "Actual (Sending) Address", "Suburb", "State", "Postcode", "Comments"];
			var postback = this.href.split(":")[1];
			var inputs = $(".contentpane :input");
			inputs.each(function(i,n) {
				var field = $(n);
				var id = field.attr("id");
				var name = id.split("_")[5];
				switch (name) {
					case "email":
						var regexp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
						if (!regexp.test(field.val())) Errors.push({Field: Fields[i], Name: name, Reason: "Invalid email address"});
						break;
					case "contacttelephone":
						if (field.val().length < 9) Errors.push({Field: Fields[i], Name: name, Reason: "Invalid phone number, please ensure that you include the area code"});
						break;
					case "contactmobile":
					case "contactfax":
					case "comments":
						break;
					default: 
						if (field.val().length < 2) Errors.push({Field: Fields[i], Name: name, Reason: "Too short"});
				}
			});
			if (Errors.length>0) {
				var msg = "The following errors have occurred:\n";
				for (var i=0; i< Errors.length; i++) {
					msg += "\n"+Errors[i].Field+ ": " + Errors[i].Reason;
				}
				alert(msg);
			}
			return Errors.length>0?false:true;
		});
		
		var SalesForceFormSubmit = $("#SalesForceFormSubmit");
		SalesForceFormSubmit.click(function(e) {
			var Errors = [];
			var inputs = $(".salesforce :input");
			inputs.each(function(i,n) {
				var field = $(n);
				switch (field.attr('id')) {
					case "email":
						var regexp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
						if (!regexp.test(field.val())) Errors.push("Invalid email address");
						break;
					case "phone":
						if (field.val().length < 9) Errors.push("Invalid phone number");
						break;
				}
			});
			if (Errors.length > 0) {
				var msg = "The following errors have occurred:\n";
				for (var i=0;i<Errors.length; i++) {
					msg += "\n - "+Errors[i];
				}
				alert(msg);
			} else {
				doSalesforce();
			}
			return false;
		});
		
	},
	getPage: function(p, alt, t) {
		if (p.length > 0) {
			if (t == "target=_blank") {
				window.open(p);
			} else  {
				window.location = p;
			}
		} else {
			if (alt) {
				if (alt.length > 0) {
					if (t == "target=_blank") {
						window.open(p);
					} else {
						window.location = alt;
					}
				}
			}
		}
		return false;
	}
};
AaE.util = {};
aae = AaE; // Thanks contentXXL

AaE.util.Cookie = {
	create: function(name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	},
	clear: function(name) {
		AaE.util.Cookie.create(name,"",-1);
	},
	read: function(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;
	}
}

AaE.util.StyleSwitcher = {
	setActive: function(title) {
		if (title) {
			var ss = $("#TextStylesheet");
			ss[0].disabled = true;
			if (ss.attr('title') == title) ss[0].disabled = false;
			AaE.util.Cookie.create("style", title, 365);
		}
	},
	getActive: function() {
		var ss = $("#TextStylesheet");
		console.log(ss[0].disabled);
		return ss.attr('title')?ss.attr('title'):null;
	},
	getPreferred: function() {
		var ss = $("#TextStylesheet");
		return (ss.attr('rel').indexOf('alt') == -1)?ss.attr('title'):null;
	}
}

AaE.util.Lightbox = function(img) {
	this.Lightbox(img);
}
AaE.util.Lightbox.prototype = {
	Lightbox: function(img) {
		var src = this;
		$("body").append("<div class=\"lightbox_background\">&nbsp;</div>");
		$(".lightbox_background").fadeTo("fast",0.7).click(function() {
			src.Hide();
		});
		if (($.browser.msie) && ($.browser.version == "6.0")) {
			$(".lightbox_background").css("height", $("body").height());
		}
		
		this.Content = img.title;
		this.Name = img.alt.toUpperCase().substring(7);
		this.Show();
	},
	Show: function() {
		$(".lightbox_background").show();
		var b = $("body");
		var html = "<div class=\"lightbox_content\"><img src=\""+this.Content+"\" alt=\"\" /><br /><p><b>"+this.Name+"</b></p><p>Click anywhere outside this image to close the window<p></div>";
		b.append(html);
		var lbc = $(".lightbox_content");
		setTimeout(function() {
			var left = (b.width() / 2) - (lbc.width() / 2);
			lbc.css("left", left);
		}, 50);
	},
	Hide: function() {
		$(".lightbox_background").remove();
		$(".lightbox_content").remove();
	}
}

AaE.LocationMap = function(args) { this.LocationMap(args); };
AaE.LocationMap.prototype = {
	LocationMap: function(args) {
		this.MapID = args.map;
		this.Map = $(args.map);
		this.Points = args.points;
		this.Map.addClass("LocationMap");
		this.attachInfo();
		this.loadPoints();
	},
	loadPoints: function() {
		var map = this.Map, mapid = this.MapID;
		for (var i=0; i<this.Points.length; i++) {
			var iPoint = this.Points[i];
			map.append("<div class=\"point\" title=\""+i+"\"><img src=\""+baseurl + "portaldata/1/images/locationmap/point_over.png" +"\" alt=\"\" /></div>");
			var point = $(mapid + " .point[title='"+i+"']");
			this.Points[i].point = point;
			point.attr("title", "");
			point.css({marginTop: iPoint.offset.y, marginLeft: iPoint.offset.x});
			this.attachEvents(this.Points[i]);
		}
	},
	attachEvents: function(p) {
		var info = this.InfoPanel, src = this;
		p.point.click(function(e) {
			var infoContent = info.find("div.content");
			if (info.css("display") != "none") {
				info.fadeOut("fast", function() {
					infoContent.hide();
				});
			}
			var html = "<div><b style=\"color: rgb(74, 176, 158);\">"+p.name.toUpperCase()+"</b></div>";
			html += "<div><b>"+p.title+"</b></div>";
			html += "<div style=\"padding-top: 10px;\">"+p.address+"</div>";
			html += "<div>"+p.suburb+"</div>";
			html += "<div>"+p.state+"</div>";
			if (infoContent.html() != html) {
				info.fadeIn("fast", function() {
					infoContent.html(html);
					infoContent.show("medium");
				});
			} else {
				infoContent.html(" ");
			}
		});
		p.point.hover(
			function(e) {
				var lmh = $("#LocationMapHover");
				lmh.remove();
				$(src.MapID).append("<div id=\"LocationMapHover\"></div>");
				lmh = $("#LocationMapHover");
				lmh.html(p.name.toUpperCase());
				lmh.css({marginTop: (p.offset.y - 32) + "px", marginLeft: (p.offset.x - 98) + "px"});
				lmh.fadeIn("fast");
				var img = $(e.target).find("img");
				img.fadeIn("fast");
			},
			function(e) {
				var lmh = $("#LocationMapHover").fadeOut("fast");
				var img;
				if ($.browser.msie) {
					img = $(e.target).find("img");
				} else {
					img = $(e.currentTarget).find("img");
				}
				img.fadeOut("fast");
		});
	},
	attachInfo: function() {
		var map = this.Map, mapid = this.MapID;
		map.append("<div class=\"info\"><div class=\"top\"><!--.--></div><div class=\"mid\"><div class=\"content\"></div></div><div class=\"bottom\"></div></div>");
		this.InfoPanel = $(mapid + " .info");
	}
}

function doSalesforce() {
	$("#SalesForce > *").each(function(i,n) {
		var visibleElement = $("#ctrl0 *[name='"+n.name+"']");
		if (visibleElement.length > 0) {
			var hiddenElement = $(n);
			hiddenElement.val(visibleElement.val());
		}
	});
	$("#SalesForce").submit();
}

/* -----------------------------------------
	RUNTIME
-------------------------------------------- */

$(function() {
	AaE.init();
});