//dojo.provide("emmapp");
//dojo.requireLocalization("emm.res", "userMessages");

// define the emmapp place holder

var emmapp_msg_show = "Show";
var emmapp_msg_hide = "Hide";
		
emmapp = { 

	ROWKEY_SEPARATOR: "_S_",
	ROWKEYNUM_ROWKEY_SEPARATOR: "__",
	WEB_DOMAIN_REGEXP: /^[a-zA-Z0-9]+([a-zA-Z0-9\-\.]+)?(:[0-9]{1,5})?($|\/|(\.[a-zA-Z]{2}($|\/)))/,
	EMAIL_DOMAIN_REGEXP: /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/,
	ATTR_nameText: "nameText",	
	SUFFIX_DOJO: "_DOJO",
//	PREFIX_DOJO: "_DOJO",
	initialized: false,
	truncat_end_mark:"...",
	
	rowKey: null,
	__validationData: [],
	__post_validationData: [],
	
	enableOnBlurValidation: false,
	isRobotSession: false,
	isGuestUser: true,
	myOrgid:null,
	
	// init
	init: function() {
	
		if ( !this.initialized ) {
			console.debug("emmapp.init");
				
			// initialize the page
			emmapp.page.init();
			
			console.debug("emmapp.init done");
			
			this.initialized = true;
		}
	},
		
	addValidationData: function(pageName, data) {
		//var size = this.__validationData.length;
		//this.__validationData[size] = {pageName:pageName, data:data};

		this.__addValidationDataEntry(this.__validationData, pageName, data);
		console.debug("emmapp.addValidationData: validation data set: " + pageName + " -> " + data);
		console.debug("All data: " + this.__validationData);
		
		// if already initalized, add to the post-initialized data
		if ( this.initialized ) {
			//size = this.__post_validationData.length;
			//this.__post_validationData[size] = {pageName:pageName, data:data};
			this.__addValidationDataEntry(this.__post_validationData, pageName, data);
		}
		
	},
	
	__addValidationDataEntry: function(validationData, pageName, data) {
		
		// make sure only add once for each page
		// for child page, replace the old data with the new one, otherwise, the old data will also show up in validation!
		for (x in validationData) {
			var pName = validationData[x].pageName;
			if ( pName == pageName ) {
				validationData[x].data = data;
				console.debug("emmapp.__addValidationDataEntry: old data replaced for page: " + pageName);
				return;
			}
		}
		
		// if no match, add the entry
		var size = validationData.length;
		validationData[size] = {pageName:pageName, data:data};

	},
	
	getValidationData: function(/*String*/actionPage) {
		if ( actionPage ) {
			var entries = [];
			for (x in this.__validationData) {
				var pageName = this.__validationData[x].pageName;
				if ( pageName == actionPage ) {
					entries.push(this.__validationData[x]);
					break;
				}								
			}
			
			return entries;
			
		} else {
			return this.__validationData;
		}
	},
	
	removeValidationData: function(/*String*/actionPage) {
		if ( actionPage ) {
			for (x in this.__validationData) {
				var pageName = this.__validationData[x].pageName;
				if ( pageName == actionPage ) {
					
					console.debug("emmapp.removeValidationData() for " + actionPage );
					
					this.__validationData[x].data = {};
					
					break;
				}								
			}			
		} 
	},
	
	getPostValidationData: function() {
		return this.__post_validationData;
	},
	
	clearPostValidationData: function() {
		this.__post_validationData = [];
	},
	
	/* get the page name that contains the element*/
	getElementPageName: function(/*string*/elementName) {
			
		for (x in this.__validationData) {
			var pageName = this.__validationData[x].pageName;
			var data = this.__validationData[x].data;
			var items = data.inputItems;
			console.debug("inputItems " + items);
			if ( items ) {
				console.debug("inputItems - length " + items.length);
				for (x in items){
					var item = items[x];
					if ( item.id == elementName ) {
						return pageName;
					}
				}				
			}
		}
		
		return null;
	},
	
	getId: function (id, rowKey) {
		var fullId = id;
		if ( id.indexOf(this.ROWKEY_SEPARATOR) < 0 ) {
			var key = rowKey;
			if ( key == null || typeof key == "undefined" ) {
				key = this.rowKey;
			}
			
			
			if ( key != null && key != "" && id.indexOf(key)<0 ) {
				fullId = key + this.ROWKEY_SEPARATOR + id;
			} 
		}
		
		return fullId;
	},
	
	// get element in page by id
	byId: function (id, rowKey) {
		return dojo.byId(this.getId(id, rowKey));
	},
	
	dijitById: function (id, rowKey) {
		var e = this.byId(id, rowKey);
		if ( e != null ) {
			return dijit.byId(e.id);
		}
		
		return null;
	},
	
	/**
	 * for a given nodeId, find the widget that is either itself or it's immediate parent
	 */
	getContainingWidget: function(/*String*/nodeId){
		// summary:
		//		Returns the parent widget of this node, if the node is a widget, return itself
		var domNode = dojo.byId(nodeId);
		for(var p=domNode; p; p=p.parentNode){
			var id = p.getAttribute && p.getAttribute("widgetId");
			if(id){
				return dijit.byId(id);
			}
		}
		return null;
	},
	
	getRowKey: function(id) {
		
		if ( id ) {
			var i = id.lastIndexOf(this.ROWKEY_SEPARATOR);
			if ( i > 0 ) {
				return id.substring(0, i);
			}
		}
		
		return null;
	},
	//get the the num from the id
	getRowKeyNum: function(id) {
		if(id.indexOf(this.ROWKEYNUM_ROWKEY_SEPARATOR) > -1){
			return id.substring(id.indexOf(this.ROWKEYNUM_ROWKEY_SEPARATOR,1)+2,id.indexOf(this.ROWKEY_SEPARATOR));
		}
		return null;
	},
	
	getRowKeyForPage: function(/*String*/pageName) {
		if ( pageName == null || pageName == "" ) {
			return "";
		}

		console.log("emmapp.getRowKeyForPage: " + pageName);

		var rowkey = "";	
		dojo.query('div[pagename=\"' + pageName + '\"]').forEach(
				function(thisObject){
					//if(dojo.attr(thisObject, "type")=="GMETA"){���ϸ�����֮��FF����follow
						//console.log("thisObject.innerHTML=" + thisObject.innerHTML);
						//console.log("thisObject.pagename=" + dojo.attr(thisObject, 'pagename'));
						//console.log("thisObject.rowkey=" +  dojo.attr(thisObject, 'rowkey'));
						//console.log("thisObject.pagekey=" +  dojo.attr(thisObject, 'pagekey'));
						rowkey = dojo.attr(thisObject, "rowkey");	
						return rowkey;
					//}
				});

		if ( rowkey == null ) rowkey = "";

		console.log("emmapp.getRowKeyForPage: " + pageName + " -> " + rowkey);

		return rowkey;
	},
	
	getPageKeyForPage: function(/*String*/pageName) {
		
		console.log("emmapp.getPageKeyForPage: " + pageName);

		var pagekey = "";
		/*
		dojo.query('div[type=\"gmeta\"]').forEach(
				function(thisObject){
					console.log("thisObject.innerHTML=" + thisObject.innerHTML);
					console.log("thisObject.pagename=" + dojo.attr(thisObject, 'pagename'));
					console.log("thisObject.rowkey=" +  dojo.attr(thisObject, 'rowkey'));
					console.log("thisObject.pagekey=" +  dojo.attr(thisObject, 'pagekey'));		
					var v_pagename = dojo.attr(thisObject, 'pagename');
					if ( v_pagename == pageName ) {
						//var rowkey = dojo.attr(thisObject, 'rowkey');
						pagekey = dojo.attr(thisObject, "pagekey");	
						
						console.log("thisObject.pagekey found:" + pagekey);		
						
						return;
					}
				});
		*/
		
		dojo.query('div[pagename=\"' + pageName + '\"]').forEach(
				function(thisObject){
					pagekey = dojo.attr(thisObject, "pagekey");	
					//alert("1: " + pagekey);
					return pagekey;
				});
		
		console.log("emmapp.getPageKeyForPage: " + pageName + " -> " + pagekey);

		if ( pagekey == null ) pagekey = "";
				
		return pagekey;
	},
	
	/**
	 * for some dojo element, the user input field is ended with _DOJO, and the real element id is a hidden field, 
	 * in this case return the user input field id
	 */
	getInputId: function(/*String*/id) {
		var _id = id + this.SUFFIX_DOJO;
		if ( dijit.byId(_id ) ) {
			return _id;
		}
		
		return id;
	},
	
	getValueElementId: function(/*string*/ id) {
		
		if ( id ) {
			var i = id.indexOf(this.SUFFIX_DOJO);
			if ( i > 0 ) {
				id = id.substring(0, i);
			}
		}
		
		return id;
	},
	
	setElementValue:function(e,oValue)
	{
		if(!e.type){
			return;
		}
		if(typeof(e)=='undefined'){
			return;
		}
		if( e.type == "select-one" || e.type == "select-multiple" ){
			for(var i=0;i<e.length;i++){
				if(e.options[i].value==oValue){
					e.options[i].selected=true;
					break;
				}
			}
		} else {
			e.value = oValue;
		}
			
	},
	
	getObjectValue: function(/*DOM Element or Dijit*/e) 
	{	
		if ( e == null ) {
			return "";
		}
		
		var obj = e;
		var value = "";
		
		if ( obj.getValue ) {
			value = obj.getValue();
		}

//		console.debug("emmapp.getObjectValue: Object " + e.id + ", value: " + obj.value);

		
		// if display value is an valid attribute, it can't be empty
		if ( obj.declaredClass == 'emm.widget.FilteringSelect' ) {
			value = obj.getDisplayedValue();
		} else if ( obj.type ) {
			//alert(e.id + " has type '" + obj.type + "'");
			
			if ( obj.type == "radio" && obj.checked ) {
				value =  obj.value;
			}
			else if ( obj.type == "select-one" || obj.type == "select-multiple" ) {
				index = obj.options.selectedIndex;
				if ( index >= 0 ) {
					value = obj.options[index].value;
				}
			} 
		}
		
		if ( (value == null || value == "") && obj.value ) {
			value = obj.value;
		}

		// if the value is tip text, return empty
		var tipText = this.getTipText(e.id);
		if ( tipText == value ) {
//			console.debug("emmapp.getObjectValue: Object " + e.id + ", tip text cleared: " + value);
			value = "";
		}

		if ( value == null ) {
			value = "";
		}

//		console.debug("emmapp.getObjectValue: Object " + e.id + ", value: " + value + ", tiptext: " + tipText);
		
		return emmapp.string.alltrim(value);	

	},
	
	getTipText: function(/*String*/id) {
		for (x in this.__validationData) {
			var data = this.__validationData[x].data;
			var items;
			
			// process the tipTextItems
			items = data.tipTextItems;
			if ( items ) {
				for (x in items){
					var item = items[x];
					
					// make sure you are using the input id, for example, some elements, the input is xxx_DOJO
					// GAGI-1181: Add new company---the tip should disappear when I click it.
					var _id = emmapp.getInputId(item.id);
					if ( _id == id ) {
						return item.tipText;
					}
				}				
			}					
		} // end for	
		
		return null;
	},
	
	
	/* show tip text to the control if the control value is empty*/
	showTipText: function(/*String*/id, /*String*/text) {
		
		if(text == null){
			return;
		}
		
		var _id = this.byId(id);
		if(_id!= null){
			if ( _id.value == "" ) {
				//_id.className = "emmapp_page_tips" ;
				//_id.className = this.__addTipsClassName(_id,"emmapp_page_tips");
				dojo.removeClass(_id, "emmapp_page_tips_clear");
				dojo.addClass(_id, "emmapp_page_tips");

				_id.value = text;
			}
		}
	},
	
	/* hide tip text from the control if the control value is the tiptext*/
	hideTipText: function(/*String*/id, /*String*/text) {
		//alert("hideTipText: " + id + "=" + text);
			var _id = this.byId(id);
			if(_id!= null){
				//_id.className = "emmapp_page_tips_clear" ;
		//		_id.className = this.__addTipsClassName(_id,"emmapp_page_tips_clear");
				
				dojo.removeClass(_id, "emmapp_page_tips");
				dojo.addClass(_id, "emmapp_page_tips_clear");
				if ( _id.value == text ) {
					_id.value = "";
				}
			}
	},
	
//	/*once add new class ,but must be keep old class*/
//	__addTipsClassName: function(/*dom object*/obj,/*string:new class name*/newClassName) {
//		var className = newClassName;
//		if(obj && obj.className){
//			var oldClassName = obj.className;
//			if(oldClassName.indexOf("emmapp_page_tips")>-1){
//				oldClassName = oldClassName.substring(0,oldClassName.indexOf("emmapp_page_tips"));
//			}else{
//				oldClassName += " ";
//			}
//			className = oldClassName + newClassName;
//		}
//		return className;
//	},
	
	showWaitCursor: function() {
		document.body.style.cursor = "wait";
		//document.body.style.cursor = url('/images/ajax-loader.gif');
	},
	
	showArrowCursor: function() {
		document.body.style.cursor = "url('/images/cursor_arrow.png')";		
	},
	showDefaultCursor: function() {
		document.body.style.cursor = 'default';
	},
	
	openWindow: function(name, url) {
	
		var w = window.open(url, name, 
				'width=1024,height=760,status=no,toolbar=no,scrollbars=yes,resizable=yes');
	    return w;
	    
	},
	
	navigateLink: function(link) {
		if (link.onclick && link.onclick()) {
		 	if (link.target) {
		 		window.open(link.href, link.target);
		 	} else {
		 		window.location.href = link.href;
		 	}
		} else {
			 eval(link.href.replace('javascript:', ''));
		}
	},
	
	 showHideNode: function(/*id: the node that triggered the action*/srcId, 
			 /*the node that needs to show or hide*/targetId) {
		 var src_node = dojo.byId(srcId);
//		 var tgt_node = dijit.byId(targetId).domNode;
		 var tgt_node = dojo.byId(targetId);
		 if ( tgt_node ) {
			 console.debug("node.style.display: " + tgt_node.style.display);
			if ( tgt_node.style.display == "none" ) {
				tgt_node.style.display = "block";
				src_node.innerHTML = emmapp_msg_hide;
			} else {
				tgt_node.style.display = "none";
				src_node.innerHTML = emmapp_msg_show;
			}
		 }
	 },
	
	 makeEnterKeyInValid: function(event) {
         var target, code, tag;
         if (!event) {
             event = window.event; //ie
             target = event.srcElement;
             code = event.keyCode;
             if (code == 13) {
                 tag = target.tagName;
                 var enter = dojo.attr(target,"enter");
                 if (tag == "TEXTAREA") { return true; }
                 else if(enter == "no"){ ;return false; }
             }
         }
         else {
             target = event.target; // Firefox
             code = event.keyCode;
             if (code == 13) {
                 tag = target.tagName;
                 var enter = dojo.attr(target,"enter");
                 if (tag == "INPUT" && enter == "no") {return false; }
                 else { return true; } 
             }
         }
     },
     goToUrlWithWaitCursor: function(url,obj){
    	 this.showWaitCursor();
    	 //if obj is a link,the style will be pointer.so change ths obj's style to 'wait'
    	 obj.style.cursor = 'wait';
    	 window.location.href = url;
     },
     excuteActionAfterCheckIsLogin: function(guestCallBack,loginCallBack){
    	 var ajaxUrl = emmapp.page.getAjaxActionUrl("check_is_login_member");
    	 var params = [];
    	 for(var i=2;i<arguments.length;i++){
    		 params.push(arguments[i]);
    	 }
    	 var that = this;
    	 function callback(response, ioArgs){
    		 if ( response.status == emmapp.ajax.JSON_STATUS_VALUE_SUCCESS && response.content) {
    			 loginCallBack.apply(that,params);
 			 }else{
 				 guestCallBack.apply(that,params);
 			 }
    	 }
    	 emmapp.ajax.doAjaxPost(ajaxUrl, callback);
     },
     getPageHtmlData: function(parent,url,method,cb){
    	 console.debug("parent"+parent);
    	 var loaderHTML = "<div style=\"text-align: center;\"><img src=\""+emmapp.page.middleLoadingImageUrl+"\" title=\"Loading\"/></div>";
    	 parent.innerHTML = loaderHTML;
    	 function callback(response, ioArgs){
    		parent.innerHTML = response;
    		if(cb){
    			cb.apply(this,arguments);
    		}
    	 }
    	 method == "post" ? emmapp.ajax.doAjaxPost(url, callback,"text") : emmapp.ajax.doAjaxGet(url, callback,"text");
     }
	
};

//define the page load event to init the emmapp
dojo.addOnLoad(function(){
	emmapp.init();
	});

//alert("emm.js done");


