﻿function createRecursiveObjects(spec) {
	//for (var item in spec) {
	var obj=document.createElement(spec.element);
	for(var attrib in spec.attributes) obj[attrib]=spec.attributes[attrib];
	if(spec.text&&spec.text!="") $(obj).html(spec.text);
	for(var style in spec.styles) obj.style[style]=spec.styles[style];
	for(var event in spec.events) $(obj).bind(event,spec.events[event]);
	for(var child in spec.children) obj.appendChild(createRecursiveObjects(spec.children[child]));
	if(spec.callback&&typeof spec.callback=="function") spec.callback(obj);
	return obj;
	//}
}
function DefaultSubmit(e,id) {
	var eventHandled=false;
	if(e.keyCode==13){
		var src=(e.srcElement||e.target).tagName;   //e.target||e.srcElement;
		if(src&&(src.toLowerCase()!="textarea")) {
			$(id).each(function() {
				if(this) {
					if(typeof (this.click)!="undefined") { eventHandled=true;this.click() }
					else if(typeof (this.onclick)!="undefined") { eventHandled=true;this.onclick.call(this) }
					else if(this.tagName.toLowerCase()=="a") {

						if(this.href.indexOf("javascript:")== -1) location.href=this.href;
						else eval(this.href.replace(/^javascript:/,""));
						eventHandled=true;
					}
				}
			});
			if(eventHandled) {
				e.cancelBubble=true;
				if(e.stopPropagation) e.stopPropagation();
				return false;
			}
		}
	}
	return true;
}

Function.prototype.bind=function(obj) {
	var method=this,
	temp=function() {
		return method.apply(obj,arguments);
	};
	return temp;
}
function Request(QueryStringField) {
	if(!window.RequestTempStorage) {
		var querystring=window.location.search.substring(1);
		var splits=querystring.split("&");

		window.RequestTempStorage=[];
		for(var x,field,i=0;field=splits[i];i++) {
			x=field.split("=");
			window.RequestTempStorage[x[0]]=x[1];
		}
	}
	return window.RequestTempStorage[QueryStringField];
}
var CookieHandler={
	setCookie:function(name,value,seconds) {
		var expires="";
		if(typeof (seconds)!='undefined') {
			var date=new Date();
			date.setTime(date.getTime()+(seconds*1000));
			expires="; expires="+date.toGMTString();
		}
		document.cookie=name+"="+value+expires+"; path=/";
	},
	getCookie:function(name) {
		name=name+"=";
		var carray=document.cookie.split(';');
		for(var c,i=0;c=carray[i];i++) {
			while(c.charAt(0)==' ') c=c.substring(1,c.length);
			if(c.indexOf(name)==0) return c.substring(name.length,c.length);
		}
		return null;
	},
	deleteCookie:function(name) { this.setCookie(name,"",-1) }
}

var site={
	handleCounters: function() {
		var objCounter=document.getElementById("counter_"+this.id); /*counters have the same id just with a counter_ prefix*/
		if(!objCounter) return;
		var maxLenValue=(this.maxLength||250);
		if($(this).hasClass("txtSummary")) maxLenValue=70; /*special case*/
		$(objCounter).text(this.value.length+"/"+maxLenValue); /*the OR filter is for the textarea part which doesn't have a maxLength since it's the only one on the page - we can use this lame hack*/
	},
	validation: {
		allowSubmit: true,
		validationFailed: function(filter,element) { /*this is an event*/ },
		validationPassed: function(filter,element) { /*this is an event*/ },
		validationCustom: function(element) { /*this is an event*/ },
		animate: function(element) {
			$(element).stop(true,true);
			$(element).focus().css("background-color","#f00").animate({ backgroundColor: "#fff" },1000,"swing");
			window.setTimeout(function() { element.style.backgroundColor="" },2000); /*jQuery animation sometimes gets stuck*/
		},
		checkForDefaultValue: function() {
			if($(this).hasClass("defaultValue")) {
				if(this.title==this.value) {
					this.error="defaultValue";
					site.validation.animate(this);
					site.validation.validationFailed("defaultValue",this);
					site.validation.allowSubmit=false;
				}
			}
		},
		email: function() {
			if(this.value.length==0||this.value.match(/^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/)) {
				site.validation.validationPassed("email",this);
				site.validation.checkForDefaultValue.call(this);
			}
			else {
				site.validation.animate(this);
				this.error="email";
				site.validation.validationFailed("email",this);
				site.validation.allowSubmit=false;
			}
			//return false;
		},
		url: function() {
			if(this.value.length==0||this.value.match(/^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/)) {
				site.validation.validationPassed("url",this);
				site.validation.checkForDefaultValue.call(this);
			}
			else {
				site.validation.animate(this);
				this.error="url";
				site.validation.validationFailed("url",this);
				site.validation.allowSubmit=false;
			}
			//return false;
		},
		required: function() {
			if(this.value.length>0) {
				site.validation.validationPassed("required",this);
				site.validation.checkForDefaultValue.call(this);
			}
			else {
				site.validation.animate(this);
				this.error="required";
				site.validation.validationFailed("required",this);
				site.validation.allowSubmit=false;
			}
			//alert("blah");
			//return false;
		},
		numeric: function() {
			if(this.value.length==0||this.value.match(/^\d+$/)) {
				site.validation.validationPassed("numeric",this);
				site.validation.checkForDefaultValue.call(this);
			}
			else {
				site.validation.animate(this);
				this.error="numeric";
				site.validation.validationFailed("numeric",this);
				site.validation.allowSubmit=false;
			}
			//return false;
		},
		validate: function(e,group) {
			group=group||"";
			site.validation.allowSubmit=true;
			$(group+" .validateEmail").change();
			$(group+" .validateUrl").change();
			$(group+" .validateRequired").change();
			$(group+" .validateNumeric").change();
			$(group+" .validateCustom").change();
			return site.validation.allowSubmit;
		},
		init: function() {
			$(".validateEmail").change(site.validation.email);
			$(".validateUrl").change(site.validation.url);
			$(".validateRequired").change(site.validation.required);
			$(".validateNumeric").change(site.validation.numeric);
			$(".validateCustom").change(function() { site.validation.validationCustom(this) });

			/*unfortunately you can't assign the validation event to the form.onsubmit because Telerik screws everything up (i think its script manager reassigns the event to prevent unintended submission)*/
			$(".triggerValidation").click(site.validation.validate);
		}
	},
	listSetup: function() {
		$(this).click(function(e) {
			var src=e.srcElement||e.target;
			if("H6|IMG".indexOf(src.tagName)== -1) return;
			var ul=$(this).find("ul").get(0);
			if(!ul) return;
			var that=this;
			if($(ul).is(":hidden")) {
				$(ul).slideDown("slow");
				$(this).addClass("expanded");
			} else {
				$(ul).hide();
				$(this).removeClass("expanded");
			}
		});
	},
	companySearch: function(e) {
		if(e.keyCode==13) {
			window.open("http://mintuk.bvdep.com/version-2009715/Search.DirectCompanyName.serv?product=mint&restart=1&display=minimal&user=catherinebr&pw=catherinebr&CompanyIdOrCompanyName="+this.value,"_blank");
			// window.open("http://mintuk.bvdep.com/Search.DirectCompanyName.serv?product=mint&restart=1&display=minimal&User=UnitasURL&pw=5OlIZS0&CompanyIdOrCompanyName="+this.value,"_blank");
			return false;
		}
	},
	newsletterSubmit: function() {
		//TODO: this is a stub
		alert("Newsletter Submit");
		/*if (site.validation.validate(null, "#boxNewsletter")) alert("Newsletter Submit");
		else alert("validation failed");
		*/
		return false;
	},
	UserTooltipIDList: [],
	CompanyTooltipIDList: [],
	setupTooltips: function() {
		/*
		here we need to retrieve User tooltips
		first we need to find all User IDs on tooltips with class UserTolltip
		Then make an ajax request to the ToolTip.ashx - all the IDs are passed in the id parameter so on the server end we end up with an array
		then we need to iterate through the returned data set and set the title attribute on the links. The ToolTip plugin looks there for the tooltip text.
		we find the relevant links by looking at the end of their href attribute. You'd think I'd be using the id attribute but I didn't think about when I first set this up.
		You can look at the end of the href attribute using jQuery by using [href$=something] - note the $ sign.

		Same for the company tooltips

		then we just need to call the tooltip plugin and it will do the rest.

		Alternative to this (the first version) is to use the plugin's built in ajax functionality. Only problem is that it creates one call per tooltip - takes too long

		*/
		$(".UserTooltip").each(function() {
			site.UserTooltipIDList.push(this.id.replace(/UserID/,""));
		});
		$(".CompanyTooltip").each(function() {
			site.CompanyTooltipIDList.push(this.id.replace(/CompanyID/,""));
		});
		var params="mode=usercompany";
		if(site.UserTooltipIDList.length>0) {
			for(var i=0;i<site.UserTooltipIDList.length;i++) {
				params+="&UserID="+site.UserTooltipIDList[i];
			}
		}
		if(site.CompanyTooltipIDList.length>0) {
			for(var i=0;i<site.CompanyTooltipIDList.length;i++) {
				params+="&CompanyID="+site.CompanyTooltipIDList[i];
			}
		}
		if(site.CompanyTooltipIDList.length>0||site.UserTooltipIDList.length>0) {
			jQuery.getJSON("ToolTip.ashx?"+params+"&blah="+new Date().getMilliseconds(),function(data) {
				if(data&&data.status=="success"&&data.response) {
					for(var i=0;i<data.response.length;i++) {
						if(data.response[i].type=="user") {
							$("a.UserTooltip[href$=UserID="+data.response[i].ID+"]").attr("title",data.response[i].ToolTip);
						}
						else if(data.response[i].type=="company") {
							$("a.CompanyTooltip[href$=CompanyID="+data.response[i].ID+"]").attr("title",data.response[i].ToolTip);
						}
					}
				}
			});
		}
		$(".UserTooltip,.CompanyTooltip,ul#menuLeft ul a").wTooltip(
			{ className: "menuToolTip",offsetY: 15,offsetX: 30 }
		);
	},
	init: function() {
		/*menu items start their life being display:none - this is because otherwise the user can briefly see the whole expanded menu when it loads - this way he can't*/
		$("ul#menuLeft li ul").css("display","block");
		if(UserSpecialFilter) {
			$("#NewsTickerContainer").hide();
			$("ul#menuLeft li ul li").css("border","none").css("display","block");
			$("ul#menuLeft").css("border","1px solid #c8c8c8");
		}
		else {
			$("ul#menuLeft").accordion(
				{
					header: "h1",
					autoHeight: false,
					fillSpace: false,
					collapsible: true,
					navigation: true,
					navigationFilter: function() {
						var curPath=location.pathname.toLowerCase().substring(1);
						var locationHref=location.href.toLowerCase();
						var thisHref=this.href.toLowerCase();

						if(curPath=="thread.aspx"&&thisHref.match("forum.aspx")) {
							return true;
						}
						/*else {
						if (thisHref == locationHref) return true;
						if (curPath != "" && thisHref.match(curPath)) return true;
						}*/
						return thisHref==locationHref;
					},
					animated: 'bounceslide',
					icons: { 'header': 'ui-icon-plus','headerSelected': 'ui-icon-minus' }
				}
			);
			site.validation.init();
			if(document.getElementById("newsTicker")) {
				$().newsTicker({
					newsList: "#newsTicker",
					startDelay: 10,
					loopDelay: 5000,
					placeHolder1: "_"
				});
			}

			window.setTimeout(
				function() { site.setupTooltips() },
				100
			);
		}
		//$(".UserTooltip").hover(site.userToolTip);
		$("input:checkbox").css("border",0);

		$(".useCounter").keyup(site.handleCounters).keyup();
		$(".useDatepicker").attr("readonly",true).datepicker({ dateFormat: "dd/mm/yy" });
		$(".dropDownList").each(site.listSetup);
		$(".companySearch").keypress(site.companySearch);
		$("#btnNewsLetterSubmit").click(site.newsletterSubmit);
		$(".defaultValue").blur(function() { if(this.value=="") this.value=this.title||"" }).focus(function() { if(this.value==this.title) this.value="" });
		$("#searchSubmit").each(function() { this.onclick=site.handleSearch });
		$(".autoFocus").focus();
		
		// tracking news clicks
		$(".news-link").click(function() {
		    var headline = $(this).html();
		    jQuery.GA.trackEvent('News', 'NewsSidebarClick', headline);
		});
       
	}
}




var DynamicContentManager=function(params) {
	var p=params||{};
	function createNewContainer(type) {
		var obj=document.createElement(type);
		document.getElementsByTagName("body")[0].appendChild(obj);
		return obj;
	};

	function getTableData() {
		$(this.container).removeClass("inProgress").addClass("inProgress");
		this.onGetDataBefore.call(this);

		$.ajax({
			type: "POST",
			url: this.dataManagerUrl,
			cache: false,
			data: this.dataManagerParams.replace("%page%",this.pageCurrent), // "{'page':" + this.pageCurrent + "}",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: this.redraw.bind(this), /*when .bind() changes the context of these functions to {this} */
			error: this.onGetDataError.bind(this)
		});
	};
	function formatUrl(strUrl) {
		if(strUrl.indexOf("?")!= -1) { /*the url contain ? so it could be something.aspx?blah=1&*/
			if(strUrl.substr(strUrl.length-1)!="?") { /*the last char is not ? so url must be like something.aspx?blah=1& */
				if(strUrl.substr(strUrl.length-1)!="&") { /*we have something.aspx?blah=1 ; we need to add the last & so that we don't end up with something.aspx?blah=1page=1 */
					strUrl+="&";
				}
				else { /*we have something.aspx?blah=1&*/ }
			}
			else { /*we have something.aspx?*/ }
		}
		else {/*we have something.aspx*/
			strUrl+="?";
		}
		return strUrl;
	};
	function checkReturnedData(data) {
		if(!data) return;
		if(data.status!="success") {
			if(!data.errorMessage) data.errorMessage="";
			alert("There was an error processing the last request\n"+data.errorMessage);
			return false;
		}
		return true;
	};

	this.container=p.container||createNewContainer("table");
	this.usePager=p.usePager; /*boolean*/
	this.pagerContainer=p.pagerContainer||createNewContainer("ul");
	this.pagerQueryStringVariable=p.pagerQueryStringVariable||"page"; /*will get appended to dataManagerUrl to retrieve correct page*/
	this.dataManagerUrl=p.dataManagerUrl||"?"; /*this makes the current page the default url*/
	this.dataManagerParams=p.dataManagerParams||"?"; /*this makes the current page the default url*/
	this.onGetDataBefore=p.onGetDataBefore||function() { };
	this.onGetDataAfter=p.onGetDataAfter||function(dataObject,textStatus) { };
	this.onGetDataError=p.onGetDataError||function(event,XMLHttpRequest,ajaxOptions,thrownError) { };

	this.myPager=null;
	this.pageCurrent=1;
	this.pagerHandler=function(pageFrom,pageTo) {
		this.pageCurrent=pageTo;
		this.reset();
	}

	this.redraw=function(data,textStatus) { /*handles call back after retrieving table data*/
		if(checkReturnedData.call(this,data.d)) {
			var newTree=createRecursiveObjects(data.d.content);
			$(this.container).empty();
			this.container.appendChild(newTree);
			this.onGetDataAfter.call(this,data.d,textStatus);

			if(!this.myPager&&this.usePager) { /*check we haven't created a pager yet, check if we have to then check if we can*/
				if(pager) this.myPager=new pager({
					mommy: this,
					container: this.pagerContainer,
					rowCount: data.d.rowCount,
					pageSize: 10,
					pageCurrent: 1,
					pagesToDisplay: 5,
					queryStringVariable: this.pagerQueryStringVariable,
					evPageChanged: this.pagerHandler.bind(this)
				});
			}
			else {
				this.myPager.rowCount=data.d.rowCount;
				this.myPager.reset();
			}
		}
		$(this.container).removeClass("inProgress");
		site.setupTooltips();
	};
	this.reset=function() {
		getTableData.call(this);
	};
}

var pager=function(params) {
	var p=params||{};
	function createNewContainer() {
		var obj=document.createElement("ul");
		obj.className="Pager";
		document.getElementsByTagName("body")[0].appendChild(obj);
		return obj;
	};
	function rangeCheck() {
		if(this.pageCurrent>Math.ceil(this.rowCount/this.pageSize)) this.pageCurrent=Math.ceil(this.rowCount/this.pageSize);
		if(this.pageCurrent<1) this.pageCurrent=1;
	};
	function handler(e) {
		e=e||event;
		var targetObj=e.srcElement||e.target;
		var objTrigger=(targetObj.tagName.toLowerCase()=="span")?targetObj.parentNode:targetObj; /*find who caused the event*/
		if(!objTrigger||objTrigger.tagName.toLowerCase()!="a") return; /*we're looking for a link with a page number*/
		var strPageLast=this.pageCurrent;
		var strPage=objTrigger.href.replace(new RegExp("^.*"+this.queryStringVariable+"=(?=\d*)"),""); /*leave only the page number, the href of the link would contain eg: http://thenumbercompanydev.s15310919.onlinehome-server.info/SelectNumber.aspx?GoTo=12 */
		if(parseInt(strPage)==NaN) return;

		this.pageCurrent=parseInt(strPage); /*now we have the page number, validate the number for max and min*/
		rangeCheck();
		this.reset();
		this.evPageChanged(strPageLast,strPage);
		return false; /*don't forget it was a link that triggered this event - stop it from redirecting*/
	};

	this.container=p.container||createNewContainer(); /*UL container where to render pages*/
	this.container.Pager=this; /*back reference*/

	this.rowCount=parseInt(p.rowCount); /*used to work out total number of pages*/
	this.pageSize=p.pageSize||10; /*rowCount/pageSize=number of pages*/
	this.pageCurrent=p.pageCurrent||1;
	this.pagesToDisplay=p.pagesToDisplay||5;
	this.queryStringVariable=p.queryStringVariable||"page"; /*this is what will be added to href in page links in the form of ?page=1*/

	this.evPageChanged=p.evPageChanged||function(pageFrom,pageTo,pager) { }; /*callback for when the page is changed*/

	this.mommy=p.mommy; /*reference back to a parent object - used */

	this.reset=function() {
		$(this.container).empty(); /*note: when row count is 0 we need to remove the pager*/
		var intPageCount=Math.ceil(this.rowCount/this.pageSize);
		this.container.onclick=handler.bind(this);


		rangeCheck();
		//we're going to display the current page in the middle and half the list on the left and on the right
		var halfFloor=Math.floor(this.pagesToDisplay/2);
		var pageFrom=this.pageCurrent-halfFloor;

		//range correction to account for the first and last pages
		if(this.pageCurrent>intPageCount-halfFloor) pageFrom=intPageCount-(halfFloor*2);
		if(pageFrom<1) pageFrom=1;

		var pageTo=pageFrom+this.pagesToDisplay-1;
		if(pageTo>intPageCount) pageTo=intPageCount;

		if(pageFrom==pageTo||intPageCount<=1) return;

		/*
		<ul id="pager">
		<li class="pagerArrowLeft"><a href="?page=1"><span>&lt;</span></a></li>
		<li class="pagerFirstVisiblePage"><a class="pagerSelectedPage" href="?page=1">1</a></li>
		<li><a href="?page=2">2</a></li>
		<li><a href="?page=3">3</a></li>
		<li><a href="?page=4">4</a></li>
		<li class="pagerLastVisiblePage"><a href="?page=5">5</a></li>
		<li class="pagerOf">of</li>
		<li class="pagerTotalPage"><a href="?page=11">11</a></li>
		<li class="pagerArrowRight"><a href="?page=6"><span>&gt;</span></a></li>
		</ul>
		*/
		if(this.pageCurrent>(1+halfFloor)) {
			this.container.appendChild(
				createRecursiveObjects(
					{
						element: "li",
						attributes: { "className": "pagerArrowLeft" },
						children: [
							{
								element: "a",
								attributes: { "href": "?"+this.queryStringVariable+"="+Math.max(1,(this.pageCurrent-this.pagesToDisplay)) },
								children: [{ element: "span",text: "<"}]
							}
						]
					}
				)
			);
		}

		for(var strLiClass,strAClass,i=pageFrom;i<=pageTo;i++) {
			strLiClass=strAClass="";
			if(i==pageFrom) strLiClass="pagerFirstVisiblePage";
			if(i==pageTo) strLiClass="pagerLastVisiblePage";
			if(i==this.pageCurrent) strAClass="pagerSelectedPage";
			this.container.appendChild(
				createRecursiveObjects(
					{
						element: "li",
						attributes: { "className": strLiClass },
						children: [
							{
								element: "a",
								attributes: { "href": "?"+this.queryStringVariable+"="+i,"className": strAClass },
								text: i
							}
						]
					}
				)
			);
		}

		this.container.appendChild(
			createRecursiveObjects(
				{ element: "li",text: "of",attributes: { "className": "pagerOf"} }
			)
		);

		this.container.appendChild(
			createRecursiveObjects(
				{
					element: "li",
					attributes: { "className": "pagerTotalPage" },
					children: [
						{
							element: "a",
							attributes: { "href": "?"+this.queryStringVariable+"="+intPageCount },
							text: intPageCount
						}
					]
				}
			)
		);

		if(this.pageCurrent<(intPageCount-halfFloor)) {
			this.container.appendChild(
				createRecursiveObjects(
					{
						element: "li",
						attributes: { "className": "pagerArrowRight" },
						children: [
							{
								element: "a",
								attributes: { "href": "?"+this.queryStringVariable+"="+Math.min(intPageCount,(this.pageCurrent+this.pagesToDisplay)) },
								children: [{ element: "span",text: ">"}]
							}
						]
					}
				)
			);
		}
	}
	this.reset();
}

jQuery(document).ready(site.init);