/**
 * Nimmt an, dass value eine JSON-Node ist, die genau einen Wert enthaelt. Unwrappt einen evtl. in einem Array steckenden Wert.
 * Bsp:
 * Liefert "foo" fuer:
 * {bar:"foo"}
 * und
 * {bar:["foo"]}
 * @param value
 */
function getJsonValue(value){

    if(dojo.isArray(value) && value.length > 0){
        return value[0];
    }else{
        return value;
    }

}

function getContextID(){
	if(typeof _CONTEXTID === "undefined" || isNaN(_CONTEXTID)){
		return -1;
	}else{
		return _CONTEXTID;
	}
}

function getDojoParentOfType(/* [DOMNode] the child to walk up from */child,/* Bsp: "dijit.Dialog" */ dojoType){

//	console.debug("child>>",child);

	if(typeof  child == "undefined" || child === null) return null;

	if(typeof child.domNode !== "undefined"){
		child = child.domNode;
	}

	var parent;
	while((parent=child.parentNode) != null){
		var parWidget = dijit.getEnclosingWidget(parent);
//		console.debug("ParWidget>>",parWidget);
		if(parWidget!=null && parWidget.declaredClass==dojoType){
		  return parWidget;
		}
		child = parent;
	}

	return null;
}

/**
 * Der Logon/Logoff Controller des Frontends
 */
var logonControllerFE = {

	rpcLogonService : new htv.rpc.htvJsonService("/ajaj?adapterName=SmdSpecAdapter&rpcCommand={method:fetch,params:[{adapterName:'FrontendLogonAdapter'}],id:1}"),

	checkLoginStatus:function(){
		if (typeof dijit != 'undefined') {
			var targetPane = dijit.byId("mpcHeadRightPane");
			if (targetPane && !window._isHtvLoginFormShown && targetPane.isLoaded) {
				dijit.byId("mpcHeadRightPane").refresh();
			}
		}
	},

	logoff:function(){
		var async = this.rpcLogonService.fetch({logout:"true"});

		async.addBoth(
				dojo.hitch(this,function(response){
					location.replace("/content/public/home.html");
				})
		);
	},

	isLoggingIn:false,

	login:function(username,password){

		if(logonControllerFE.isLoggingIn) return;

		logonControllerFE.isLoggingIn = true;
		password = dojox.encoding.digests.MD5(password, dojox.encoding.digests.outputTypes.Hex);

		var async = this.rpcLogonService.fetch({"username":username,"password":password,doMD5Digest:false});

		dojo.addClass(dojo.byId('loginSubmit'),'submitButtonActive')

		async.addErrback(
				function(response){
					logonControllerFE.isLoggingIn = false;
					var msg = 	" Login failed because of a connection problem.<br/>"
								+ "We apologise and kindly ask you to try again later.<br/>";

					dialogControllerFE.showDefaultDialog(msg,DLG_BTNSET_OK);
					dojo.removeClass(dojo.byId('loginSubmit'),'submitButtonActive')
				}
		);

		async.addCallback(
				function(response){
					logonControllerFE.isLoggingIn = false;
					var success = getJsonValue(response.success);
					if(success === true || success == "true"){

						dijit.byId("mpcContentPane").refresh();
						dijit.byId("mpcHeadRightPane").refresh();


					}else{
						var backenderror 	= getJsonValue(response.backenderror);
						var timeout 		= getJsonValue(response.timeout);

						var msg;

						if(timeout === true || timeout == "true"){
							msg = "Login failed because of a timeout while connecting to our authentication server.<br/>"
									+ "We apologise and kindly ask you to try again later.<br/>"
									+ "This error triggered the automatic creation of an error ticket to our support, so we're aware of the failure.";
						}else
						if(backenderror === true || backenderror == "true"){
							msg = "Login failed because of a authentication server failure.<br/>"
									+ "We apologise and kindly ask you to try again later.<br/>"
									+ "This error triggered the automatic creation of an error ticket to our support, so we're aware of the failure.";
						}else{
							msg = "Login failed. Please check username and password.";
						}

						dialogControllerFE.showDefaultDialog(msg,DLG_BTNSET_OK);
						dojo.removeClass(dojo.byId('loginSubmit'),'submitButtonActive')
					}
				}
		);
	}
};

/**
 * Constants fuer die Typisierung von Controlgruppen in Dialogfeldern
 */
var DLG_BTNSET_OK = 1,
    DLG_BTNSET_OK_CANCEL = 2,
    DLG_BTNSET_YES_NO_CANCEL = 3;

var dialogControllerFE = {

	formPostService : new htv.rpc.htvJsonService("/ajaj?adapterName=SmdSpecAdapter&rpcCommand={method:fetch,params:[{adapterName:'FormPostAdapter'}],id:1}"),

	showDefaultDialog:function(messageHTML,/* see htvFrontend.js >> var DLG_* */buttonSet){

        var dlg = dijit.byId("stdFrontendDialog");
        dlg.setDialogHTML(messageHTML);
        if(!buttonSet){
            dlg.chooseDlgSet(DLG_BTNSET_OK);
        }else{
            dlg.chooseDlgSet(buttonSet);
        }
        dlg.show();
    },

	showErrorDialog:function(message,code,cause){
		this.showDefaultDialog("Error: "+message+"<br/>\n"+code+"<br/>\n"+cause,DLG_BTNSET_OK);
	},

	showFormDialogSuccessText:function(){
		var succesTextContainer = dojo.query("[id*=successTextContainer]","formFrontendDialog")[0];
		var errorTextContainer 	= dojo.query("[id*=errorTextContainer]","formFrontendDialog")[0];
		var formContainer 		= dojo.query("[id*=formContainer]","formFrontendDialog")[0];

		dojo.style(formContainer , 			{display:"none"});
		dojo.style(errorTextContainer , 	{display:"none"});
		dojo.style(succesTextContainer , 	{display:"block"});
	},

	showFormDialogErrorText:function(){
		var succesTextContainer = dojo.query("[id*=successTextContainer]","formFrontendDialog")[0];
		var errorTextContainer 	= dojo.query("[id*=errorTextContainer]","formFrontendDialog")[0];
		var formContainer 		= dojo.query("[id*=formContainer]","formFrontendDialog")[0];

		dojo.style(formContainer , 			{display:"none"});
		dojo.style(errorTextContainer , 	{display:"block"});
		dojo.style(succesTextContainer , 	{display:"none"});
	},

	showFormDialog:function(formURL,submitCallback,submitErrback){

		var dlg = dijit.byId("formFrontendDialog");

        dlg.attr("href",formURL);
		dlg.attr("submitCallback",submitCallback);
		dlg.attr("submitErrback",submitErrback);
		
        dlg.show();
		
	},

	submitForm:function(formValues,senderDlg){

		// CS: Fetching handlers from DLG
		var callback 	= senderDlg.attr("submitCallback");
		var errback 	= senderDlg.attr("submitErrback");

		

		var async = this.formPostService.push({mode:"postForm"},formValues);

        if(errback){
            async.addErrback(errback);
        }else{
            async.addErrback(function(response){
                dialogControllerFE.showErrorDialog("The form could not be successfully transmitted. Please try again later.");
            });
        }

        if(callback){
            async.addCallback(callback);
        }


	}



};

/**
 * Der Panecontroller des Frontends
 */
var paneControllerFE = {

	load:function(sender,link,targetPaneID,preventHistoryEntry){

		//alert(link);
		this.fixLink(sender);
        
		if(sender && sender.tagName && sender.tagName.toLowerCase() == "a"){
			if(dojo.attr(sender,"resource")){
				link = dojo.attr(sender,"resource");
			}
			if(dojo.attr(sender,"_target")){
				targetPaneID = dojo.attr(sender,"_target");
			}
		}

		var targetPane = dijit.byId(targetPaneID);

		if(targetPane && (targetPane instanceof dojox.layout.ContentPane || targetPane instanceof dijit.layout.ContentPane)){

			if(!targetPane.isLoaded){
				// CS: Doppelklick auf den selben Link abfangen
				if(targetPane.attr("href") == link){
					return;
				}else{
					targetPane.cancel();
				}
			}

			if(!preventHistoryEntry) dojo.back.addToHistory(
					appStateControllerFE.captureHistoryNode([targetPaneID],
															targetPaneID,
															link)
					);

			if(link.toLowerCase().indexOf("http://") === 0 && link.toLowerCase().indexOf("http://"+location.host+"/") !== 0 
					||
			   !link.match(/^[A-Za-z0-9\/\:\-\%\_\.]+\.htm[l]?/igm) && !link.match(/^[A-Za-z0-9\/\:\-\%\_\.]+\.jsp[x]?/igm)){


				if(link.toLowerCase().indexOf("http://"+location.host+"/") === 0){
					link = link.replace(/^http:\/\/[^\/]+(.*)$/ig,"$1");
				}
				link = "/content/public/external.html?wrapMedia=true&r="+escape(link.replace());
			}
			targetPane.attr("href",link);
		}else{
			dialogControllerFE.showErrorDialog("Der Link konnte aufgrund eines Fehlers der Portals leider nicht geladen werden. "
					+ "Bitte wenden Sie sich per Mail an admin@hellotvcontent.com um Unterst&uuml;tzung zu erhalten.");
		}

		return true;
	},

	resizeContentPane:function(contentSize){

		var height = contentSize.h;

//		// CS: Falls die uebergebene contenSize von einer tieferliegenden AutoResizePane stammt, dann muss die Differenz zwischen deren offset
//		// vom oberen Bildschirmrand und dem der mpcContentPane mit auf die Groesse der mpcContentPane aufgerechnet werden, sonst wird mpcContentPane
//		// zu klein.
//		if(contentSize.y){
//			var mpcPaneCoords = dojo.coords(dijit.byId("mpcContentPane").domNode);
//			var diff = contentSize.y - mpcPaneCoords.y;
//			height += diff;
//		}

		var naviHeight = dojo.coords("mainNavContainer").h;

		if(height < naviHeight){
			height = naviHeight+50;
		}

		var s = {h:(height < 700 ? 700+250 : height+250)};
		dijit.byId("masterPortalContainer").resize(s);
		dijit.byId("mpcLeadingPane").resize(s);
		dijit.byId("mpcContentPane").resize({h:s.h-240});
		
	},

	fixLink:function(target){

		if(target && target.href && !dojo.attr(target,"_treated") && !dojo.attr(target,"resource")){
			dojo.attr(target,"resource",""+target.href);
			dojo.attr(target,"_treated",true);
			target.href = "javascript:void(0)";
		}
	}

};

var appStateControllerFE = {


	captureHistoryNode:function(/* array von widgetIDs von ContentPanes,
	deren href in die history aufgenommen werden soll,
	bevor der neue Inhalt geladen wird */
			capturePaneIDs,newResourceTargetPaneID,newResourceHref){

		var historyNode = {
			paneIDs:[],
			paneHrefs:[],
			forwardTargetPaneID:newResourceTargetPaneID,
			forwardHref:newResourceHref
		};

//		if(dojo.isArray(capturePaneIDs)){
//
//			for(var i = 0; i < capturePaneIDs.length; i++){
//				var paneID 	= capturePaneIDs[i];
//				var pane	= dijit.byId(paneID);
//
//				if(pane == null || !dojo.isString(pane.attr('href')) || pane.attr('href').length < 1){
//					continue;
//				}
//				var resource= pane.attr('href');
//
//				historyNode.paneIDs[i] 		= paneID;
//				historyNode.paneHrefs[i] 	= resource;
//			}
//		}

		// CS: Return State Object
//		console.debug("Fuege History Node hinzu >> ",historyNode.paneHrefs);
		return {
			historyItem : historyNode,

			back:function(){
//				console.debug("History Back. Gehe zu >> ",this.historyItem.forwardHref);
//				for(var i = 0; i < this.historyItem.paneIDs.length; i++){

					paneControllerFE.load(null,
							this.historyItem.forwardHref,
							this.historyItem.forwardTargetPaneID,
							true
							);
//				}
			},

			forward:function(){
//				console.debug("History Forward. Gehe zu >> ",this.historyItem);
				paneControllerFE.load(null,
									this.historyItem.forwardHref,
									this.historyItem.forwardTargetPaneID,
									true
									);
			},

			changeUrl:true

//			handle:function(/* this may be String 'back' or 'forward' */ histType){
//
//
//			}
		};
	}

};

var eventControllerFE = {

	dispatchGlobalClicks:function(e){
		if(e && e.originalTarget && dojo.isString(e.originalTarget.tagName)){

			switch(e.originalTarget.tagName.toLowerCase()){

				case "a": paneControllerFE.load(e.originalTarget); break;

			}

			switch(e.rangeParent.tagName.toLowerCase()){

				case "a": paneControllerFE.load(e.rangeParent); break;

			}

		}
	},

	dispatchGlobalMouseOvers:function(e){

		if(e && e.originalTarget && dojo.isString(e.originalTarget.tagName)){

			switch(e.originalTarget.tagName.toLowerCase()){

				case "a": paneControllerFE.fixLink(e.originalTarget); break;

			}

		}
	}

};
