
/******************************************************************
 * Functionality of add-to-cookbook-links
 ******************************************************************
 * methods are CHAINABLE in order to force a sequential workflow!
 *****************************************************************/


function cookbookDialog () {
	
	this.DEBUG_2_CONSOLE = false;
	
	this.user_is_logged_in = false;

	// holds an instance of the dialogs DOM-Objects
	this.dialog_object			= null;
	this.publishFirstDialog		= null;
	this.publishBePatientDialog	= null;

	// html attribute holding link-ids
	this.CLICKED_LINK_ATTRIBUTE_NAME	= 'activecblink';
	// get-param-name holding link-id after login
	this.CLICKED_LINK_GETPARAM_NAME 	= 'gotocblink';
	// ID for efficient acces, if necessary
	this.CLICKED_LINK_ID 				= 'cblinkactive';
	// actual id of the clicked link
	this.clicked_link_id_numeric 		= 0;

	// get-param-name indicating failed login attempt
	this.LOGIN_FAILED_GETPARAM_NAME 	= 'loginfail';
	
	/**
	 * prints to firebug console
	 * @param string message
	 * @param int level // 1=info, 2=warn, 3=error
	 */
	this.debug = function(message, level) {
		if (!$.browser.msie && this.DEBUG_2_CONSOLE==true) {
			switch (level) {
				case 3:		console.error(message);		break;
				case 2:		console.warn(message);		break;
				default:	console.info(message);
			}
		}
	};
	
	
	this.init = function() {
		this.debug("starte INIT()", 1);
		
		// get a single publishFirst-Dialog if available:
		this.publishFirstDialog = $("#publishFirstDialog:first");
		$("body").remove("#publishFirstDialog");
		$('body').append(this.publishFirstDialog);		
		
		// get a single bePatient-Dialog (waiting for deployment) if available:
		this.publishBePatientDialog = $("#publishBePatientDialog:first");
		$("body").remove("#publishBePatientDialog");
		$('body').append(this.publishBePatientDialog);
		
		// get a singlular cookbook-Dialog:
		this.dialog_object = $("#cookbookDialog:first");
		$("body").remove("#cookbookDialog");
		$('body').append(this.dialog_object);

		// var user_is_logged_in is defined in cookbookDialog.tag:		
		this.user_is_logged_in = user_is_logged_in;
				
		this.initBodyClickHandler(this)
			.initLinkIds(this)
			.initLinkEvents(this)
			.initDialogDataLogin(this)
			.initDialogDataCookbook(this)
			.setPreviouslyClickedLinkId(this)
			.scrollToPreviouslyClickedLink(this)
			.clickPreviouslyClickedLink(this);
	};	
	
	
	/**
	 * HELPER: delivers complete url to the calling login form
	 * @param string targetUrl
	 * @return string
	 */
	this.getCompleteTargetURL = function(clicked_link_id_numeric) {
		targetUrl = self.location.href;
		var paramSeparator = (self.location.search) ? '&' : '?';
	   	targetUrl += paramSeparator + this.CLICKED_LINK_GETPARAM_NAME + '=' + clicked_link_id_numeric;
	   	return targetUrl;
	};
	
	
	/**
	 * HELPER: Provides the id from GET-Parameter (gotoCbLink=)
	 * @return int|boolean
	 */
	this.getValueFromGetParam = function(paramName) {
		var q = window.location.search;
		
		if (!q) return false;
		var paramPos = q.indexOf(this.CLICKED_LINK_GETPARAM_NAME);
		if (paramPos == -1) return false; 
		q = q.substring(paramPos);
		
		var ampPos = q.indexOf('&');
		if (ampPos != -1) {
			q = q.substring(0, ampPos);
		}
		
		var linkId = (q.substring(this.CLICKED_LINK_GETPARAM_NAME.length +1));
		if (!linkId.length) return false;
		return linkId;
	};
	
	
	/**
	 * declares an event for closing the dialog 
	 * @param int dummyInt
	 * @return int
	 */
	this.initBodyClickHandler = function(me) {
		
		$("body").click( function(event) {
	        var clickedElement = event.target;
	        
	        // keine Aktion, falls ein element des dialog-divs geklickt wurde
	        var child_clicked = false;
	        me.dialog_object.each(function() {
	            if ($(clickedElement).parents().index($(this)) >= 0) {
	            	child_clicked = true;
	            }
	        });
	        
	        if (!child_clicked) {
		        // Klick auf den oeffnen-link soll nicht schliessen
		        if (!$(clickedElement).hasClass('ilAddKochbuch')) {
		        	me.hideDialog();
		        }
	        }

		});
		return me;
	};

	/**
	 * initialzes the login dialog elements
	 * @param int dummyInt
	 * @return int
	 */
	this.initDialogDataLogin = function(me) {
		if (me.user_is_logged_in) {
			me.debug("Login-Dialog wird nicht initialisiert!", 2);
			return me;
		}
		me.dialog_object.find('.close').click(function(){
			me.hideDialog();
			return false;
		});
		return me;
	};
	

	/**
	 * initialzes the add2cookbook dialog elements
	 * @param dummyInt
	 * @return
	 */
	this.initDialogDataCookbook = function(me) {
		if (!me.user_is_logged_in) {
			me.debug("Cookbook-Dialog wird nicht initialisiert!", 2);
			return me;
		}
		
		$('.kb_dialog .close').click(function(){
			me.hideDialog();
			return false;
		});
		
		$('.kb_dialog .submit').click(function(event) {
			var submitButton = event.target;
			var targetURL = '/account/cookbook/addrecipe.htm';
			var par = $(this).parent().parent();
			var params = '';
			$(par).find('input[type=text], input:checked[type=radio]').each(function() {
				params += this.name+'='+ encodeURIComponent(this.value) +'&';
			});
			$(par).find('input[type=hidden]').each(function() {
				params += this.name+'='+encodeURIComponent(this.value) + '&';
			});
			
			params += 'debug=true';
			jQuery.post(targetURL, params, function (data) {
				var result  = data.split("|");
				var status  = result[0];
				var msg     = result[1];
				var cbid    = result[2];
				if (status == 'OK') {
					self.location='/account/cookbook/arrangecookbook.htm' + '?cbId=' + cbid;
				} else {
					$('.recipeToCookbookError').text(msg);
				}
			});
		});
		return me;
	};
	
	 
	/**
	 * applies sequential numbers to every cookbook link
	 * @param dialogObj
	 * @return
	 */
	this.initLinkIds = function(me) {
		var linkCounter = 0;
		var msg = "Numeriere die Links durch... von 1 bis ";
		$(".ilAddKochbuch").each(function(){
			linkCounter++;
			$(this).attr(me.CLICKED_LINK_ATTRIBUTE_NAME, linkCounter);
		});
		msg += linkCounter;
		this.debug(msg, 1);
		return me;
	};
	
	
	/**
	 * adds a click-event to every cookbook link
	 * @param dialogObj
	 * @return
	 */
	this.initLinkEvents = function(me) {
		$(".ilAddKochbuch").removeAttr('href')
			.css({cursor: 'pointer'})
			.click(function(event){
				event.preventDefault();
				if (!me.user_is_logged_in) {
					clicked_link_id_numeric = $(this).attr(me.CLICKED_LINK_ATTRIBUTE_NAME);
					targetUrl = me.getCompleteTargetURL(clicked_link_id_numeric);
					me.debug( "targetUrl: "+targetUrl , 2);
					$("#redirectUrl", me.dialog_object).val(targetUrl);
				}
				else {
					$("#cmsId", me.dialog_object).val($(this).attr("cmsId"));
					$("#recipeTitle", me.dialog_object).val($(this).attr("recipeTitle"));
				}
				
				if ( $(this).hasClass("publishFirstLink") ) {
					me.debug( "REZEPT IST NICHT FREIGEGEBEN" , 2);
					me.showPublishFirstDialog($(this));
				}
				else if ( $(this).attr("cmsId") == '0' ) {
					me.debug( "REZEPT IST FREIGEGEBEN UND NOCH NICH IN BLAST" , 2);
					me.showPublishBePatientDialog($(this));
				}
				else {
					me.debug( "REZEPT IST VOLLSTAENDIG FREIGEGEBEN" , 2);
					me.showCookbookDialog($(this));
				}
				return false;
			}); 
		return me;
	};
	
	
	/**
	 * determines and sets the id of the previously clicked link
	 * @param dummyInt
	 * @return
	 */
	this.setPreviouslyClickedLinkId = function(me) {
		var previously_clicked_link_id = me.getValueFromGetParam(this.CLICKED_LINK_GETPARAM_NAME);
		me.debug("previously_clicked_link_id ist " + previously_clicked_link_id, 1);
		me.clicked_link_id_numeric = previously_clicked_link_id;
		return me;	
	};
	
	
	/**
	 * Scrolls to teh y-position of the previously clicked link
	 * @param dummyInt
	 * @return
	 */
	this.scrollToPreviouslyClickedLink = function(me) {
		if (!me.clicked_link_id_numeric) {
			me.debug("Kein link zum Hin-Scrollen!", 1);
			return me;
		}
	    // ID auslesen und anspringen
		this.debug("suche nach Link mit " + this.CLICKED_LINK_ATTRIBUTE_NAME + "=" + me.clicked_link_id_numeric, 1);
		$(".ilAddKochbuch").each(function(){
			if ($(this).attr(me.CLICKED_LINK_ATTRIBUTE_NAME) == String(me.clicked_link_id_numeric)) {
				me.debug("... gefunden!", 1);
				// set an ID for further access later
				$(this).attr("id", me.CLICKED_LINK_ID);
				lnkPos = $(this).offset();
				delta_y = 200;
				new_y = lnkPos.top - delta_y;
				me.debug("Scrolle nach " + new_y + " ...", 1);
				self.scrollTo(0, new_y);
			}
		});
		return me;
	};
	
	

	this.clickPreviouslyClickedLink = function() {
	    if (!this.CLICKED_LINK_ID) {
	    	this.debug("Kein Link zum Klicken definiert", 2);
	    	return this;
	    }
	    this.debug("Klicke auf den Link mit der ID " + this.CLICKED_LINK_ID, 1);
	    $("#"+this.CLICKED_LINK_ID).trigger('click');
	    return this;
	};

	
	this.platznachunten = function(objTop, objHeight) {
		var my_top = objTop - $(window).scrollTop();
		my_top += objHeight;
		return $(window).height() - my_top;
	};
	
	
	/**
	 *	returns left/top as a seperated String: 88|222
	 *  this will be where the Layer is being displayed.
	 * @param linkObj
	 * @param dialogObj
	 */
	this.getDialogDisplay_left_and_top = function(linkObj, dialogObj) {
		lnkPos = linkObj.offset();
		lnkTop = lnkPos.top;
		lnkHeight = linkObj.height();
		
		// calculate, if the layer can be shown below the link without being cut
		var lueckeUnten = this.platznachunten(lnkTop, lnkHeight);
		var dlgHoehe = dialogObj.height();
		if (dlgHoehe +20 > lueckeUnten) {
			dialogPos_y = lnkTop - dlgHoehe - 30;
		}
		else {
			dialogPos_y = lnkTop + lnkHeight + 2;
		}
		dialogPos_x = lnkPos.left - 14;
		var left_and_top_string = dialogPos_x + '|' + dialogPos_y;
		return left_and_top_string;
	}
	
	
	this.showAnyDialog = function(linkObj, dialogObj) {
		this.hideDialog();
		dialogObj.removeClass("hide");
		var left_and_top = this.getDialogDisplay_left_and_top(linkObj, dialogObj).split('|');
		var left = left_and_top[0];
		var top	 = left_and_top[1];
		this.debug("layer "+ dialogObj.attr('id') +" an pos "+left+" / "+top+" einblenden...", 1);
		dialogObj.css('left', left+'px').css('top', top+'px').fadeIn();
	}
	
	
	
	/**
	 * Shows dialog below the given link object
	 * @param linkObj
	 */
	this.showCookbookDialog = function (linkObj) {
		this.showAnyDialog(linkObj, this.dialog_object);
	};
	
	/**
	 * Shows dialog below the given link object
	 * @param linkObj
	 */
	this.showPublishFirstDialog = function (linkObj) {
		this.showAnyDialog(linkObj, this.publishFirstDialog);
	};
	
	/**
	 * Shows dialog below the given link object
	 * @param linkObj
	 */
	this.showPublishBePatientDialog = function (linkObj) {
		this.showAnyDialog(linkObj, this.publishBePatientDialog);
	};
	
	/**
	 * hides any dialog
	 */
	this.hideDialog = function () {
		$('.kb_dialog').hide();
		$('.kb_dialog').addClass("hide");
	};
	
	
	this.init();
}


