Wpl = {};

WplUser = function () {} ;
// stores the currently logged in user (statically - sort of)
WplUser._current = {};
WplUser.prototype.setUserId = function (userId) {
	this._userId = userId;
}
WplUser.prototype.setCredentials = function (creds) {
	this._credentials = creds;
}
WplUser.prototype.setLoggedIn = function (loggedIn) {
	this._loggedIn = loggedIn;
}

WplUser.prototype.getUserId = function () {
	return this._userId;
}
WplUser.prototype.getCredentials = function () {
	return this._credentials;
}
WplUser.prototype.getLoggedIn = function () {
	return this._loggedIn;
}
// Does the user have the supplied array of credentials?
WplUser.prototype.hasCredentials = function (creds) {
	var thiss = this;
	return creds.all(function (aCred) {
		return (thiss._credentials.indexOf(aCred) >= 0);
	});
}
// effectively static!
WplUser.getCurrent = function () {
	return WplUser._current;
}
// effectively static!
WplUser.setCurrent = function (u) {
	WplUser._current = u;
}

// holds meta data about restricted links and opens up lightboxes etc. when they are clicked.
WplLinks = {};
WplLinks._linkData = {};
WplLinks._baseUrl = "";
WplLinks.setBaseUrl = function (v) {
	this._baseUrl = v;
}
WplLinks.makeFullUrl = function (url) {
	return this._baseUrl + url;
}
WplLinks.setupLink = function (linkElId, loginReq, credentials) {
	var el = $(linkElId);
	if (!el) {
		alert("Invalid link element supplied");
	}
	this._linkData[linkElId] = {
		el: el,
		loginReq: loginReq,
		creds: credentials		
	}
	Event.observe(el, 'click', this.handleLink, false);
}
WplLinks.handleLink = function (evt) {
	var el = Event.element(evt);
	if (!WplLinks._canFollow(el.id)) {
		Event.stop(evt);
		
		var url = WplLinks._baseUrl + "/users/restrictedLightbox";
		var ld = WplLinks._linkData[el.id];
		if (ld) {
			url += "/loginReq/" + (ld.loginReq ? "1" : "0");
			url += "/credentials/" + escape(Object.toJSON(ld.creds)) + "/";
		}
		var callback = function (success) {
			if (success) {
				// the lightbox link handler was successful!
				window.location = el.href;
			}
		}
		WplDialog.open(
			"Login stuff in here? ... <a href='javascript:void(Dialog.closeInfo())'>close</a>", 
			"Login", 
			callback,
			url
		);
	}
}
WplLinks._canFollow = function (linkId) {
	var curUser = WplUser.getCurrent();
	var ld = this._linkData[linkId];
	if (!ld) {
		alert("no data for link " + linkId);
		return false;
	}
	if (!curUser) {
		// no current user to check creds on
		return false;
	}
	
	if (ld.loginReq && !curUser.getLoggedIn()) {
		// alert("User not logged in");
		return false;
	}
	
	if (ld.creds && !curUser.hasCredentials(ld.creds)) {
		// alert("User doesn't have creds");
		return false;
	}
	return true;
}


// use this for lightbox functionality 
WplDialog = {};
WplDialog._callbackFunc;
WplDialog._canCloseFunc;

// leave url null if you want to include text instead
WplDialog.openAlert = function (text, width, height, callbackFunc) {
	if (!width) {
		width = 500;
	}
	
	var callback = function (win) {
		return WplDialog.windowCloseCallback();
	}
	
	this._callbackFunc = callbackFunc;
	
	Dialog.info(
		text + "<br/><br/><input class='blueButton' type='button' value='Ok' onclick='WplDialog.finish(true)' />",
		{className: "bluelighting", width:width, height:height, closable: 1}
	);
		
}
// leave url null if you want to include text instead
WplDialog.openText = function (text, width, height) {
	if (!width) {
		width = 500;
	}
	this._callbackFunc = null;
	Dialog.info(
		text,
		{className: "bluelighting", width:width, height:height, closable: 1}
	);
}
// leave url null if you want to include text instead
WplDialog.openUrl = function (url, title, callbackFunc, width, height, canCloseFunc) {
	if (!height) {
		height = 400;
	}
	if (!width) {
		width = 500;
	}
	
	
	var callback = function (win) {
		return WplDialog.windowCloseCallback();
	}
	
	this._callbackFunc = callbackFunc;
	this._canCloseFunc = canCloseFunc;
	
	Dialog.info(
		'',
		{className: "bluelighting", width:width, height:height, url: url, 
		closable: 1, closeCallback: callback}
	);
}

// Window was closed!
//
WplDialog.windowCloseCallback = function (win) {
	var canClose = 1;
	if (this._canCloseFunc) {
		canClose = this._canCloseFunc();
	}
	
	if (canClose && this._callbackFunc) {
		this._callbackFunc(false);
	}
	
	return canClose;
}

// This gets called by the lightbox to close itself - success is used to determine if
// the process succeeded - it gets passed into the callback function.
WplDialog.finish = function (success) {
	if (this._callbackFunc) {
		this._callbackFunc(success);
	}
	this._closeAll();
}
// close all lightboxes in the current window
WplDialog._closeAll = function () {
	Dialog.closeInfo(); 
}

// this is used inside a lightbox to close itself (calls function in parent)
WplDialog.closeLightbox = function (success) {
	if (parent.WplDialog) {
		parent.WplDialog.finish(success);
	} 
}
// open a lightbox which reloads the parent page if it is "successful"
WplDialog.openPageReload = function (url, width, height) {
	this.openUrl(
		url, 
		'', 
		function (success) {
			if (success) {
				window.location.reload(true);
			}
		},
		width, 
		height
	);
}
WplDialog.setCanCloseFunc = function (func) {
	this._canCloseFunc = func;
}


// Wpl Pluspanel
//
// A commonly used nav compoent.  There's a sf helper for it.
Wpl.PlusPanel = {};
Wpl.PlusPanel.attach = function (panelId, linkEl, initialState) {
	var panelEl = $(panelId);
	var linkEl;
	if(linkEl)
	{
		linkEl = $(linkEl);
	}
	else
	{
	var linkEl = $('a' + panelId.toUpperCase().substr(0, 1) + panelId.substr(1));
	}
	var observer = function (event) {
		if (Element.hasClassName(linkEl, 'plus')) {
			// currently closed - open it
			Element.removeClassName(linkEl, 'plus');
			linkEl.setAttribute('title','hide this panel\'s content');
			Element.show(panelEl);
		} else {
			// currently open - close it
			Element.addClassName(linkEl, 'plus');
			linkEl.setAttribute('title','show this panel\'s content');
			Element.hide(panelEl);
		}
		Event.stop(event);
	}
	
	Event.observe(linkEl, 'click', observer);
}

Wpl.PlusPanelSwitcher = {};
Wpl.PlusPanelSwitcher.attach = function (panelId, panelId2 ,linkEl, initialState) {
	var panelEl = $(panelId);
	var linkEl;
	
	if(linkEl)
	{
		linkEl = $(linkEl);
	}
	else
	{
	var linkEl = $('a' + panelId.toUpperCase().substr(0, 1) + panelId.substr(1));
	}
	var observer = function (event) {
		if (Element.hasClassName(linkEl, 'plus')) {
			// currently closed - open it
			Element.removeClassName(linkEl, 'plus');
			linkEl.setAttribute('title','hide this panel\'s content');
			Element.show(panelEl);
			
			if (panelId2)
			{
				//Element.addClassName($(panelId2), 'dontDisplay');
				//Element.hide($(panelId2));
				$(panelId2).style.display = 'none';
			}
		} else {
			// currently open - close it
			Element.addClassName(linkEl, 'plus');
			linkEl.setAttribute('title','show this panel\'s content');
			Element.hide(panelEl);
			
			if (panelId2)
			{	
				//Element.removeClassName($(panelId2), 'dontDisplay');
				//Element.show($(panelId2));
				$(panelId2).style.display = 'block';
			}
		}
		Event.stop(event);
	}
	
	Event.observe(linkEl, 'click', observer);
}

// works with the corresponding PHP class
Wpl.AjaxRequest = function (url, data, callback) {
	url = WplLinks.makeFullUrl(url);
	var success = function (xmlObj, jsonResponse) {
		if (callback) {
			callback(jsonResponse);
		}
	}
	var failure = function (xmlObj) {
		alert("Failure");
	}
	var exception = function (xmlObj, ex) {
		alert("Exception " + Object.inspect(ex));
	}
	// make the request
	var req = new Ajax.Request(url, {
		method: 'post',
		parameters: data,
		onComplete: success,
		onFailure: failure,
		onException: exception
	});
}


// Ratings slider
Wpl.SuperRatings = function (id, itemClass, itemId, userRating, membersRating) {
	this._id = id;
	this._itemClass = itemClass;
	this._itemId = itemId;
	this._userRating = userRating;
	this._membersRating = membersRating;
	
	this._isMouseDown = false;
	
	this._init();	
}

// this fires when the user mouses over the rating - it switches it from the global member rating 
// to the personal one
Wpl.SuperRatings.prototype._mouseOver = function () {
	var id = this._id;
	Position.clone($('superRatings' + id + 'G'), $('superRatings' + id + 'U'));
	$('superRatings' + id + 'Desc').innerHTML = "Your personal rating:";
	if (this._userRating != null) {
		$('superRatings' + id + 'Percent').innerHTML = this._userRating + "%";
	} else {
		$('superRatings' + id + 'Percent').innerHTML = "Not rated";
	}	
}

// fires when the user is no longer over the rating div - switches back to the 
// global member rating
Wpl.SuperRatings.prototype._mouseOut = function () {
	var id = this._id;
	if (!this._isMouseDown) {
		// This 'isMouseDown' check is essential for smoothness on internet explorer, without
		// it, this event fires constantly when the mouse is dragged.  Retarded.
		$('superRatings' + id + 'U').style.left = "-3000px";
		$('superRatings' + id + 'Desc').innerHTML = "Members' rating:";
		
		if (this._membersRating != null) {
			$('superRatings' + id + 'Percent').innerHTML = this._membersRating + "%";
		} else {
			$('superRatings' + id + 'Percent').innerHTML = "Not rated";
		}
	}
}

Wpl.SuperRatings.prototype._init = function () {
	var thiss = this;
	var id = this._id;
	
	Event.observe($('superRatings' + id), "mouseover", function (event){
		thiss._mouseOver();
	});
	
	Event.observe($('superRatings' + id), "mouseout", function (event){
		thiss._mouseOut();
	});
	
	Event.observe(window, "load", function (event) {
		// overwrite the non-javascript form with a pimpy version
		// $('superRatings' + id + 'Form').innerHTML = '';
		
		// add in handle:
		var track = $('superRatings' + id + 'UTrack');
		var handle = html.div("");
		Element.addClassName(handle, "userRatingHandle");
		track.appendChild(handle);
		
		new Control.Slider(handle, track,{
			sliderValue: thiss._getUserRatingForSlider() * 2,
			range:$R(0,200),
				
		    onSlide:function(v){
				thiss._isMouseDown = true;
				$('superRatings' + id + 'Percent').innerHTML='' + Math.round(v/2) + "%";
		    	$('superRatings' + id + 'UTrackFill').style.width = v + "px";
		    },
		    
		    onChange:function(v){
		    	thiss._isMouseDown = false;
		    	thiss._userRating = Math.round(v/2);
		    	$('superRatings' + id + 'Percent').innerHTML='' + thiss._userRating + "%";
		    	// save new value via ajax:
				var callback = function (response) {
					if (response.success) {
						// need to tell the user their rating was saved
						thiss._showRatingSaved();
					} 
				}
				var data = {
					itemClass: thiss._itemClass,
					itemId: thiss._itemId,
					rating: Math.round(v/2)
				};
				new Wpl.AjaxRequest("news/userRating", data, callback)	    	
		    }
		});
	});
}
Wpl.SuperRatings.prototype._getUserRatingForSlider = function () {
	if (this._userRating == null) {
		return 50;
	} else {
		return this._userRating;
	}
}
// inform the user that their rating was saved
Wpl.SuperRatings.prototype._showRatingSaved = function () {
	// $('superRatings' + this._id + 'Percent').innerHTML  += " (rating saved)";
	var id = this._id;
	
	var div = html.div();
	Element.addClassName(div, 'superRatingsSaved');
	div.appendChild(html.p('Your rating has been saved'));
	
	var input = html.input({type: 'button', value: 'ok'});
	Element.addClassName(input, 'blueButton');
	Event.observe(input, 'click', function () {
		$('superRatings' + id).parentNode.removeChild(div);
	});
	
	div.appendChild(input);
	
	$('superRatings' + id).parentNode.appendChild(div);
	
	Position.clone($('superRatings' + id), div);
}


// this is for the drop down menus, written by Robin
Wpl.initNav = function (id) {
	if (!id) {
		id = "navSecondary";
	}
	var browserName=navigator.appName; 
	var browserVer=parseInt(navigator.appVersion); 
	if (browserName=="Microsoft Internet Explorer" && browserVer>=4)
	{
		Event.observe(window, "load", function() 
		{
			var sfEls = document.getElementById(id).getElementsByTagName("li");
			for (var i=0; i<sfEls.length; i++) {
				sfEls[i].onmouseover=function() {
					if(this.className.search(/sfhide/) != -1)
					{
						this.className=this.className.replace(new RegExp(" sfhide\\b"), " sfhover");
					}
					else
					{
						this.className+=" sfhover";
					}
				}
				sfEls[i].onmouseout=function() {
					this.className=this.className.replace(new RegExp(" sfhover\\b"), " sfhide");
				}
			}
		});
	}

}

// this is for drop down menus where the secondary nav is also a drop down
Wpl.initExtraDropNav = function () {
	var browserName=navigator.appName; 
	var browserVer=parseInt(navigator.appVersion); 
	if (browserName=="Microsoft Internet Explorer" && browserVer>=4)
	{
	Event.observe(window, "load", function() 
	{
		var sfEls = document.getElementById("nav").getElementsByTagName("li");
			for (var i=0; i<sfEls.length; i++) {
				sfEls[i].onmouseover=function() {
					if(this.className.search(/sfhide/) != -1)
					{
						this.className=this.className.replace(new RegExp(" sfhide\\b"), " sfhover");
					}
					else
					{
						this.className+=" sfhover";
					}
				}
				sfEls[i].onmouseout=function() {
					this.className=this.className.replace(new RegExp(" sfhover\\b"), " sfhide");
				}
			}
	});
	
	}

}

// attach one of those annoying messages into a form field which disappear when you click into it
Wpl.attachFormElMessage = function (el, message) {
	Event.observe(
		window, 
		"load", 
		function() {
			if (!Form.Element.getValue(el)) {
				el.value = message;
			}
		}
	);
	
	Event.observe(
		el,
		"blur",
		function() {
			if (!Form.Element.getValue(el)) {
				el.value = message;
			}
		}
	);
	
	Event.observe(
		el,
		"focus",
		function() {
			if (Form.Element.getValue(el) == message) {
				el.value = '';
			}
		}
	);
	
	if (el.wplFormItem) {
		// the form element is associated with a wplFormItem, so we attach a special 
		// validator to disallow submission in the case of default message
		// not being changed!
		el.wplFormItem.addValidator(
			new WplFormValidators.validators.notEqual(message, "'" + message + "' must be changed!")
		);
	}
}

// make a link print the page
Wpl.attachPrintLink = function (elId) {
	var el = $(elId);
	
	Event.observe(el, 'click', function (evt) {
		print();	
		Event.stop(evt);
	}, false);
}

// update an image - does a page redirect in ie :(
Wpl.updateImageCache = function (imageUrl, urlRedirect)
{

	document.write("<iframe name='imageRefresher' id='imageRefresher' src='" + imageUrl + "' style='display: none;'></iframe>");
	$('imageRefresher').contentWindow.location.reload(true);
	if (Prototype.Browser.IE) {
		window.location = urlRedirect;
	}
}