﻿Cv.namespace("Cv.Base");

/**
 * Resources for this namespace are stored in the <Cv> namespace. E.g: Cv.en.js
 */

Cv.Base.UI = Class.create({
	currentState : null,
	isStateCheckerEnabled : false,
	
	initialize: function() {
			
	},
	
	/**
	 * Call this function to enable state checking. It checks on a regular interval if the hash part has changed.
	 * If the hash part changes it fires the "cv:statechange" event. 
	 * Use Event.observe(document, "cv:statechange", function(e) { alert(e.memo.state); }); to react on this event.
	 * @param {integer?} opt_ms Defines the amount of milliseconds for the interval.
	 */	
	enableStateChecker : function(opt_ms) {
		if (this.isStateCheckerEnabled)
			return;
		
		this.isStateCheckerEnabled = true;
		
		if (opt_ms == null || opt_ms == "undefined")
			opt_ms = 50;
		
		var docMode = document.documentMode;
		var oldIE = (Prototype.Browser.IE && (!docMode || docMode <= 7));
		
		if (oldIE) {
			$$("body")[0].insert("<iframe id=\"iestatecheckeriframe\" style=\"visibility:hidden\" src=\"javascript:0\" tabindex=\"-1\" />");
			this.stateIFrame = $("iestatecheckeriframe").contentWindow;
		}
		if ("onhashchange" in window && !oldIE) {
			Event.observe(window, "hashchange", this._checkState.bindAsEventListener(this));
			this._checkState();
		}
		else
			setInterval(this._checkState.bind(this), opt_ms);		
	},
	
	
	_checkState : function() {
		if (this.stateIFrame != null) {			
			if (this.currentState != location.hash) {
				//change in document
				
				this.currentState = location.hash;
				this.stateIFrame.document.open().close();
				this.stateIFrame.location.hash = location.hash;
				document.fire("cv:statechange", {state : location.hash});
			}
			else if (this.currentState != this.stateIFrame.location.hash) {
				//history change from back button
				
				this.currentState = this.stateIFrame.location.hash;
				location.hash = this.stateIFrame.location.hash;
				document.fire("cv:statechange", {state : this.stateIFrame.location.hash});
			}
		}
		else {
			if (this.currentState != location.hash) {
				document.fire("cv:statechange", {state : location.hash});
				this.currentState = location.hash;
			}			
		}		
	},
	
	updateLanguageLinks : function() {
		$$(".languageLink").each(function(obj) {
										if (obj.href.indexOf("#") > -1) {
											var s = obj.href.substring(0, obj.href.indexOf("#"));
											obj.href = s + location.hash;
										}
										else {
											obj.href = obj.href + location.hash;
										}
									});
	},
	
	/**
	 * Stores all messages on page
	*/
	_messageItems : new Array(),
	
	/**
	 * Displays a message on top of the UI
	 * Use CvBaseUI.showMessage("Hello, I'm <b>alive</b>!", $("message")); in your code to show a message.
	 * @param {string} text the text to show.
	 * @param {obj} container An element where the messagebox should be inserted to.
	 * @param {bool?} opt_fadeOut Defines if the text should disappear after some time
	 * @param {integer?} opt_ms Defines for how long the message should be visible (if opt_fadeOut == true)
	 */	
	showMessage : function(text, container, opt_fadeOut, opt_ms, opt_messageClass) {
		if (opt_messageClass == null)
			opt_messageClass = "message";
		else
			opt_messageClass += " message";
		
		var flash = false;
		if (container.innerHTML == "<div id=\"c_" + container.id + "\" class=\"" + opt_messageClass + "\">" + text + "</div>")
			flash = true;
			
		container.innerHTML = "<div id=\"c_" + container.id + "\" class=\"" + opt_messageClass + "\">" + text + "</div>";
		
		if (flash)
			new Effect.Highlight("c_" + container.id, {duration : 0.2, startcolor : "#ff9f49", restorecolor: "#fff1a8", keepBackgroundImage : true});
				
		if (this._messageItems[container.id] != null) 
			clearTimeout(this._messageItems[container.id]);
		
		if (opt_fadeOut != null && opt_fadeOut) {
			opt_ms = opt_ms == null ? 2500 : opt_ms;
			this._messageItems[container.id] = setTimeout(function(obj) { return(function() { container.innerHTML = ""; }); }(this), opt_ms);
		}
	},
	
	hideMessage : function(opt_Container) {
		var id = "message";
		if (opt_Container != null)
			id = opt_Container.id;
		
		$(id).innerHTML = "";
		
		if (this._messageItems[id] != null) 
			clearTimeout(this._messageItems[id]);
	},
	
	showLoadingMessage : function(opt_cssClass) {
		var messageClass = "message";
		if (opt_cssClass != null)
			messageClass += " " + opt_cssClass;
		
		$("message").innerHTML = "<div id=\"cv_Message\" class=\"" + messageClass + "\">" +
									"<img src=\"/media/imgs/wait.gif\" style=\"height:8px\" />&nbsp;&nbsp;" + Cv.Utils.Resource.getResource("CV_Loading") + 
								"</div>";
	},
	
	hideLoadingMessage : function() {
		$("message").innerHTML = "";
	},
	
	showUserStatus : function(e) {
		Event.observe(document, "cv:signin", this.showUserStatus.bindAsEventListener(this));
		Event.observe(document, "cv:signout", this.showUserStatus.bindAsEventListener(this));
		Event.observe(document, "cv:providerselected", this.showUserStatus.bindAsEventListener(this));
		Event.observe(document, "cv:creditsreduced", this._creditsReduced.bindAsEventListener(this));
		
		var s = "";
		
		if (Cv.Utils.isNullOrEmpty(this.getToken())) {
			$("userStatus").innerHTML = "<img src=\"/media/imgs/lock.png\" /> " +
											"<a href=\"/" + CvCurrentLanguage + "/generator/\">" + 
												Cv.Utils.Resource.getResource("CV_SignIn") + 
											"</a>";	
		}
		else {
			if (CvCurrentApplication == "generator" || CvCurrentApplication == "bulk") { //From AppBasePage.cs
				var provider = "";
				if (!Cv.Utils.isNullOrEmpty(this.getProviderName()))
					provider = "<img src=\"/media/imgs/team_header.png\" style=\"height:12px; width:20px\" /> " + 
								"<a id=\"changeProvider\" href=\"javascript:;\">" + this.getProviderName() + "</a> &nbsp; ";
				
				$("userStatus").innerHTML = provider +
											"<img src=\"/media/imgs/user.png\" style=\"height:12px; width:12px\" />" +
											"<span>" + this.getUsername() + "</span> &nbsp; " +
											"<img src=\"/media/imgs/lock.png\" /> " +
											"<a href=\"javascript:;\" id=\"signOut\">" + 
												Cv.Utils.Resource.getResource("CV_SignOut") + 
											"</a>";
				
				Event.stopObserving("signOut", "click")
				Event.observe("signOut", "click", this.signOut.bindAsEventListener(this));
				
				if (!Cv.Utils.isNullOrEmpty(this.getProviderName())) {
					Event.stopObserving("changeProvider", "click")
					Event.observe("changeProvider", "click", this.selectProvider.bindAsEventListener(this));
				}
			}
			else {
				$("userStatus").innerHTML = "<img src=\"/media/imgs/lock.png\" /> " +
											"<a href=\"/" + CvCurrentLanguage + "/generator/\">" + 
												Cv.Utils.Resource.getResource("CV_SignIn") + 
											"</a>";	
			}
		}
	},
	
	_creditsReduced : function() {
		if ($("providerCredits") != null)
			$("providerCredits").innerHTML = "Credits";
	},
	
	_loadCredits : function() {
		CvJavascriptLoader.load("/api/beetaggcore/javascript/Cv.BeeTaggCore.js");
		CvBeeTaggCore.getProviderOverview(this.getToken(),
									this.getProviderId(),
									null, 
									null,
									null, 
									null, 
									null,
									null,
									null, 
									null,
									null,
									null,
									this._loadCreditsCallback, 
									this);
	},
	
	_loadCreditsCallback : function(res) {
		$("providerCredits").innerHTML = res.ProviderOverview.Credits + " Credits";
	},
	
	/**
	 * Checks if user and provider are available. If not it shows the sign in box and provider select box
	 * @return false if user OR provider are not available, true if both are.
	 */	
	isUserAndProvider : function() {
		if (Cv.Utils.isNullOrEmpty(this.getToken())) {
			this.signIn(true);
			return false;
		}		
		if (Cv.Utils.isNullOrEmpty(this.getProviderId())) {
			this.selectProvider();
			return false;
		}		
		return true;
	},
	
	/**
	 * Checks if user is available. If not it shows the sign in box
	 * @return false if user is not available, true if it is
	 */	
	isUser : function(showSignInBox, withProviderSelection) {
		if (Cv.Utils.isNullOrEmpty(this.getToken())) {
			if (showSignInBox == null || showSignInBox == true) {
				withProviderSelection = withProviderSelection == null ? true : withProviderSelection;	
				this.signIn(withProviderSelection);
			}				
			return false;
		}		
		return true;
	},
	
	/**
	 * Checks if provider is available. If not it shows the provider select box
	 * @return false if provider is not available, true if it is
	 */	
	isProvider : function() {
		if (Cv.Utils.isNullOrEmpty(this.getProviderId())) {
			this.selectProvider();
			return false;
		}			
		return true;
	},
	
//	_signInCallback : function(e) {
//		this.signIn(true);
//	},
	
//	_visitMy : function() {
//		location.href = "/" + CvCurrentLanguage + "/my/";
//	},
	
	signIn : function(withProviderSelect) {
		CvJavascriptLoader.load("/apps/my/javascript/Cv.My.UI.js");
		var my = new Cv.My.UI();
		my.signIn(true);
	},
	
	signOut : function() {
		CvJavascriptLoader.load("/apps/my/javascript/Cv.My.UI.js");
		var my = new Cv.My.UI();
		my.signOut();
	},
	
	selectProvider : function() {
		CvJavascriptLoader.load("/apps/my/javascript/Cv.ProviderManager.UI.js");
		CvProviderManagerUI.selectProvider();
	},
	
	getToken : function() {
		if (Cv.Utils.isNullOrEmpty(Cv.Utils.Cookie.getCookie("token")))
			return null;
		return "enc_" + Cv.Utils.Cookie.getCookie("token");
	},
	
	getProviderId : function() {
		if (Cv.Utils.isNullOrEmpty(Cv.Utils.Cookie.getCookie("providerid")))
			return null;
		return Cv.Utils.Cookie.getCookie("providerid");
	},
	
	getProviderName : function() {
		return Cv.Utils.Cookie.getCookie("providername");
	},
	
	getUsername : function() {
		return Cv.Utils.Cookie.getCookie("username");
	},
	
	getUserId : function() {
		return Cv.Utils.Cookie.getCookie("userid");
	},
	
	/**
	 * Adds string to debug window defined in Masterpage.
	 * usage: CvBaseUI.debug(data.replaceAll("\n", "<br />"));
	 * @return false if provider is not available, true if it is
	 */	
	debug : function(str) {
		if ($("debug") == null) {
			alert("No debug container found. You have to place a div with id = debug to the page.");
		}
		$("debug").innerHTML = str;
	},
	
	deactivateButton : function(linkButtonObj) {
		linkButtonObj.className = "linkButtonInactive buttonLarge";
	},
	
	activateButton : function(linkButtonObj) {
		linkButtonObj.className = "linkButton buttonLarge";
	},
	
	isActiveButton : function(linkButtonObj) {
		return !linkButtonObj.hasClassName("linkButtonInactive");
	}
});


if (!window.CvBaseUI) 
	CvBaseUI = new Cv.Base.UI();
	

