dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dojo.data.ItemFileWriteStore");
var doRunAjax = true;
var lbsnValue = null;
var supraKeyboxIdValue = null;
var supraLockboxes = Array();
var sentrilockLockboxes = Array();

var Misc = {
		updateClock: function() {
			var crtLocalTime = new Date();
			// check if 10 minutes have passed since we started the clock
			// and do a clock update
			var updateAfterMinutes = 10;
			var minutesPassed = dojo.date.difference(crtDate, crtLocalTime, 'minute');
			if( minutesPassed >= updateAfterMinutes) {
				crtDate = new Date();
				dojo.xhrGet({
			           url: '/login/update-clock',
			           load: function(data, ioArgs) {
							dojo.byId('clock').innerHTML = data;
						},
			           error: function(data, ioArgs){},
			           content: {}
				});	
			} else {
				// normalize the date by adding the timezone offsets, both browser and SS user account 
				var userLocalTime = new Date(crtLocalTime.getTime()+(userTimeZoneOffset * 1000) + (crtLocalTime.getTimezoneOffset() * 60 * 1000));
				var dateStr = dojo.date.locale.format(userLocalTime, {timePattern: "h:mm a", selector: "time"});
				if(dojo.byId('clock'))
					dojo.byId('clock').innerHTML = dateStr.replace(':','<blink>:</blink>').toLowerCase();
			}
			setTimeout(Misc.updateClock, clockUpdateInterval);

		},
		
		runAjaxByGet: function(url, targetDivId) {
			var targetDivNode = dojo.byId(targetDivId);
			if(!targetDivNode && targetDivId) {
				// search for standard targetDivNode
				targetDivId = 'listTableContent';
				targetDivNode = dojo.byId('listTableContent');
			}
			var widgetTargetDivNode = dijit.byId(targetDivId);
			if(!widgetTargetDivNode && targetDivId) {
				widgetTargetDivNode = new dijit.layout.ContentPane({}, targetDivId);
				widgetTargetDivNode.attr('onLoad', function(data){
					// for Lite Users make sure we gray out the links
					if(typeof LiteAccount != 'undefined') LiteAccount.start();
				});
			}
			dojo.query(".loadingOverlay").orphan();
			if(targetDivId)
				var loadingDiv = dojo.create('DIV', {'class': 'loadingOverlay', 'innerHTML': 'Loading...'}, targetDivId, 'first');
			
			if(url.lastIndexOf("partial") == -1) {
				if(!url.match(/\/$/)) url += "/";
				url += "partial/1/";
			}
			if(doRunAjax) {
				dojo.xhrGet({
					url: url,
					handleAs: "text",
					load: function(response){
						if(widgetTargetDivNode)
							widgetTargetDivNode.attr('content', parseHtmlForWidgets(response));
						if(typeof callAfterAjaxLoad != 'undefined') {
							// call this function instead and return;
							eval(""+callAfterAjaxLoad+"()");
							return;
						}
			     	},
			     	error: function(error){
			        	dojo.query(".loadingOverlay").orphan();
			        	if(targetDivId)
			        		var errorDiv = dojo.create('DIV', {'class': 'loadingOverlay', 'innerHTML': 'GET Error processing search request.'}, targetDivId, 'first');
			        	console.log(error);
			        }
			    });
				doRunAjax = false;
				setTimeout('doRunAjax=true;',500);
			} else {
				console.log('only 1 request per 0.5 secs');
			}
		},
		/**
		 * Submit the form by Ajax
		 * If targetDivId and loadUrl then they will be used to load a specific url into the targetDivId
		 * If onDesktop is supplied the above 2 params will be used to load a desktop section  
		 */
		runFormWithAjax: function (element, targetDivId, loadUrl, onDesktop) {
			var form = getForm(element);
			var formObj = form;
			var parentDivNode = dojo.byId(targetDivId);
			var moreContent = {partial : 1, ajax : 1};
			
			if (/msie/i.test (navigator.userAgent)) {
				// get form id using this method instead of form.getAttribute('id')
				// the above call will return a HTML object if an element with name id exists in the form 
				// see info about bug here http://www.sixteensmallstones.org/ie-javascript-bugs-overriding-internet-explorers-documentgetelementbyid-to-be-w3c-compliant-exposes-an-additional-bug-in-getattributes
				// http://webbugtrack.blogspot.com/2007/08/bug-152-getelementbyid-returns.html
				var formId = form.getAttributeNode("id").value;
				// submit by ajax
				var idValue = null;
				// fix IE bug when form contains input with name id
				// get the input name id value
				dojo.query("[name=id]", formObj).forEach(function(el){idValue = el.value;});
				if(idValue) {
					// set id content param for the ajax request 
					moreContent = {partial : 1, ajax : 1, id : idValue};
					// rename input name id so that the form get's sent
					dojo.query("[name=id]", formObj).forEach(function(el){
						el.setAttribute("name",el.getAttribute("name")+"_");
						el.setAttribute("id",el.getAttribute("id")+"_");
					});
				}
				if(formId) formObj = formId;
			}
			var xhrArgs = {
		        form: formObj,
		        handleAs: "json",
		        content: moreContent,
		        load: function(data){
					dojo.query("#" + parentDivNode .getAttribute("id") + " div.loadingOverlay").orphan();
		        	if(loadUrl && parentDivNode)
		        		if(onDesktop) Desktop.loadSection(targetDivId, loadUrl);
		        		else Misc.runAjaxByGet(loadUrl, targetDivId);
		        	else {
		        		// return true as success
		        		return true;
		        	}
		        },
		        error: function(error){
		        	dojo.query("#" + parentDivNode .getAttribute("id") + " div.loadingOverlay").orphan();
		        	if(loadUrl && parentDivNode)
		        		if(onDesktop) Desktop.loadSection(targetDivId, loadUrl);
		        		else Misc.runAjaxByGet(loadUrl, targetDivId);
		        	else {
		        		// return false, since an error was given
		        		return false;
		        	}
		        }
			}
			var loadingDiv = dojo.create('DIV', {'class': 'loadingOverlay', 'innerHTML': 'Loading...'}, targetDivId, 'first');
			var deferred = dojo.xhrPost(xhrArgs);
		},
		onPreviewUrlContent: function(dialogUrl, myWidth, myHeight) {
			try {
				var dialog = dijit.byId('PreviewUrlContentDialog');
				if(!dialog) {
					dialog = new dijit.Dialog({id : 'PreviewUrlContentDialog'});
				}
				dialog.attr('href',dialogUrl);
				var viewport=dijit.getViewport();
				if (typeof myWidth == 'undefined'){
					myWidth = '800';
				}
				if (typeof myHeight == 'undefined'){
					myHeight = '600';
				}
				var width=Math.min(viewport.w-20, myWidth);
				var height=Math.min(viewport.h-20, myHeight);									 
				dialog.resize({w:width,h:height});
				dialog.show();				
				return false;
			} catch (ex) {
				return false;
			}
		},
		
		addFilteringSelectQuickSearchFunctionality: function(inputId, type, lbsn) {	
			//reset the combobox
			// set the corresponding params on the comboBox
			var listingStore = '';
			
			var store = Misc.getDropDownDataStore(inputId, type, lbsn);
			
			dijit.byId(inputId).attr('store', store);
			dijit.byId(inputId).attr('searchAttr', 'name');
			dijit.byId(inputId).attr('ignoreCase', true);
			dijit.byId(inputId).attr('autoComplete', false);
			dijit.byId(inputId).attr('highlightMatch', 'all');
			dijit.byId(inputId).attr('labelType', 'text');
			dijit.byId(inputId).attr('queryExpr', "*${0}*");
//			dijit.byId(inputId).attr('hasDownArrow', false);
			dijit.byId(inputId).attr('searchDelay', 350);
			
			dojo.connect(dijit.byId(inputId), 'onKeyUp', null, function(event){
				if(event.keyCode == '13' || event.keyCode == '35' || event.keyCode == '36' || event.keyCode == '38' || event.keyCode == '40') 
					return;
				if(dojo.byId(inputId).value.length < 3 || dojo.byId(inputId).value.match(/Please Select/i) || dojo.byId(inputId).value.match(/Type in/i)) {
					// do nothing if string is smaller than 3 
					return;
				}
				try {
					dijit.byId(inputId).store = Misc.getDropDownDataStore(inputId, type, lbsn, true);
				} catch(e) {
					console.log(e);
				}
			});
			var hideResultListFunction = dijit.byId(inputId)._hideResultList;
			dojo.connect(dijit.byId(inputId), '_hideResultList', null, function(){
				if(dijit.byId('loadingMenu_'+inputId)) dijit.byId('loadingMenu_'+inputId).destroy(false);
				// call the hideResultList function
				hideResultListFunction;
			});
			var startDropdownSearchFunction = dijit.byId(inputId)._startSearch;
			dojo.connect(dijit.byId(inputId), '_startSearch', null, function(){
				Misc.createLoadingMessage(inputId);
				// call the startDropdownSearch function
				startDropdownSearchFunction;
			});
			
			// get existing open function
			var openFunction = dijit.byId(inputId).open; 
			dojo.connect(dijit.byId(inputId), 'open', null, function(){
				// hide the loadingMessage
				if(dijit.byId('loadingMenu_'+inputId)) dijit.byId('loadingMenu_'+inputId).destroy(false);
				// call the original openFunction
				openFunction;
			});
			dojo.connect(dijit.byId(inputId), 'doHighlight', null, function(label, find){
				// Add greedy when this.highlightMatch=="all"
				var modifiers = "i"+(this.highlightMatch=="all"?"g":"");
				var escapedLabel = this._escapeHtml(label);
				find = dojo.regexp.escapeString(find); // escape regexp special chars
				var regExp = new RegExp("("+ find +")", modifiers);
				var ret = escapedLabel.replace(regExp,'<strong>$1</strong>');
						return ret;// returns String, (almost) valid HTML (entities encoded)
			});
			
		},
		getDropDownDataStore: function(inputId, type, lbsn, fromTyping) {
			if (type == 'lockboxes')
				var	searchUrl = "/contacts/list-json/lbsn_number/"+lbsn+"/"+type+"/1/?qsearch=" + dojo.byId(inputId).value;
			else if (type == 'lbsn' && !('undefined' == typeof dijit.byId('user_id')))					
				searchUrl = "/contacts/list-json/user_id/"+dijit.byId('user_id').value+"/"+type+"/1/?qsearch=" + dojo.byId(inputId).value;
			else if (!('undefined' == typeof fromTyping))
                searchUrl = "/contacts/list-json/"+type+"/1/fromTyping/1?qsearch=" + dojo.byId(inputId).value;
            else
				searchUrl = "/contacts/list-json/"+type+"/1/?qsearch=" + dojo.byId(inputId).value;
			var dataStore = new dojo.data.ItemFileReadStore({url: searchUrl});
			
			return dataStore;
		},
		createLoadingMessage: function(inputId) {
			// create the loading popup
			dojo.require("dijit.Menu");
			if(dijit.byId('loadingMenu_'+inputId)) 
				var loadingMenu = dijit.byId('loadingMenu_'+inputId);
			else {
				var loadingMenu = new dijit.Menu({id: 'loadingMenu_'+inputId, targetNodeIds: [inputId], 'class': 'dropDownLoadingMsg'});
				loadingMenu.addChild(new dijit.MenuItem({ label: "Loading...please wait.", disabled: false, 'class': "dropDownLoadingMsg"}));
			}
			dijit.popup.open({
			    parent: dijit.byId(inputId),
			    popup: loadingMenu,
			    around: dijit.byId(inputId).domNode,
			    orient: {'BR':'TR', 'BL':'TL', 'TR':'BR', 'TL':'BL'}
			});
		},        
        syncronizeAccordions: function(widget){
            widget.connect(this, 'onclick',function(){ 
                selectedId = this.selectedChildWidget.domNode.id[2];	
                dijit.byId('emails').selectChild('st'+(parseInt(this.selectedChildWidget.domNode.id[2])+4));
            });
        },
        handlePopupClosing: function(){
            if (window.parent.dijit.byId('popupDialogBox')){
                window.parent.dijit.byId('popupDialogBox').hide();
                window.parent.location.href=window.parent.location.href;
		    }
        },
        handlePopupClosing2: function(){
        	if(window.parent) window.parent.scroll(0,0);
        	if (window.parent.dijit.byId('popupDialogBox')){
        		window.parent.dijit.byId('popupDialogBox').attr('onHide', function(){
            		window.parent.location.href=window.parent.location.href
            	});
		    }
        },
        
    	openInDialog: function(element, title){
    	  //dojo.require("dijit.Dialog");
    	  // create the dialog:
    	  //myDialog = new dijit.Dialog({
    	  //    title: title,
    	  //    style: "width: 900px; height: 700px;",
    	  //    href: element.href
    	  //});
    	  //myDialog.show();
    		Dialog.showInIframe( title, element.href,'900','700');
    	},
        onClickUpgradeDialog: function(controller) {
			if(!dijit.byId('dialogBox')) {
				dialog = new dijit.Dialog({id : 'dialogBox', title : 'Upgrade'});
			}
			dijit.byId('dialogBox').setHref('/products/'+controller+'/upgrade/');
			dijit.byId('dialogBox').show();
			return false;
		},
		prepareForLockboxChange: function() {
			if(dojo.query('.propertyDetailForm').length > 0) {
				if(dojo.byId('lbsn')) {
					lbsnValue = dojo.attr('lbsn','value');
				}
				if(dojo.byId('supra_keyboxid')) {
					supraKeyboxIdValue = dojo.attr('supra_keyboxid','value');
				}
			}	
		},
		
		checkForLockboxChanges:function() {
			if(dojo.attr('supra_keyboxid','value') != supraKeyboxIdValue) {
				// suprakeybox was changed so check for overwriting 
					return Misc.overWriteLockboxCheck(dojo.attr('supra_keyboxid','value'), supraLockboxes);
			}
			if(dojo.attr('lbsn','value') != lbsnValue) {
				// lbsn was changed so check for overwriting 
				return Misc.overWriteLockboxCheck(dojo.attr('lbsn','value'), sentrilockLockboxes)
			}
			return true;
		},
		
		overWriteLockboxCheck: function(newLockboxValue, lockboxes)
		{ 
			result = false;
			for(var i=0; i<lockboxes.length; i++) {
		    	if (lockboxes[i] == newLockboxValue) { result = true; break; }
		  	} 
		  	if (result == false){
		  		for(var i=0; i<lockboxes.length; i++) {
		    		if (lockboxes[i] == '00'+newLockboxValue || '00'+lockboxes[i] == newLockboxValue) { result = true; break; }
		  		} 
		  	}
		  	if (result){
				if (confirm('WARNING: This lockbox is currently assigned to another listing. Click OK if you want to un-assign it from the current listing and assign it to this one.'))
					return true;
				else { 
					return false;
				}
			}	
			return true;
				
		},
		setSubmitValue: function(submitValueName, element) {
			if(typeof mainFormsetSubmitValue == 'function') {
				mainFormsetSubmitValue(element); 			
			}; 
			dojo.query('[name=submitValue]',getForm(element)).forEach(function(node){node.value = submitValueName});
		}, 
		doSubmitSSForm: function(submitValueName, element) {
			Misc.setSubmitValue(submitValueName, element);
			getForm(element).submit();
			return false;
		},
		resizeParentPopUp: function(popupid) {
			if(window.parent && window.parent.Dialog) {
				 window.parent.Dialog.resizeIframe(popupid);
			 }
		},
		pause: function(millis) {
			var date = new Date();
			var curDate = null;
			do { curDate = new Date(); } 
			while(curDate-date < millis)
		}
};

function strip(html)
{
   var tmp = document.createElement("DIV");
   tmp.innerHTML = html;
   return tmp.textContent||tmp.innerText;
}

var Forms = {
        showLabels : false,
		processOptionalElements: function (formId) {
			var index = 0;
			var hasVisibleElements = false;
			dojo.query('.formElCellOptional', formId).forEach(function(el){
				dojo.query('.answerTd', el.parentNode).addClass('hidden');				    			    				
                dojo.addClass(el,'hidden');                
				var inputs = dojo.query('.formElOptional', el);
				//console.log(inputs);
				if(inputs.length > 0) {
					var myDijit = dijit.byNode(inputs[0]);
					//console.log(myDijit.baseClass);
					if(myDijit.declaredClass == 'dijit.form.TextBox' && myDijit.get('value')) {
						Forms.showElement(myDijit.get('id'));
						hasVisibleElements = true;
					} else if(myDijit.declaredClass == 'dijit.form.ComboBox') {
						if(myDijit.get('value')) {
							//console.log(myDijit.get('id'));
							Forms.showElement(myDijit.get('id'));
							hasVisibleElements = true;
						}
					}
				}
			});
			
			if(!hasVisibleElements) {
				// we should at lease show the first element
				dojo.query('.formElCellOptional', formId).forEach(function(el){
					if(index++ == 0) {
						var inputs = dojo.query('.formElOptional .dijitInputContainer input', el);
						Forms.showElement(inputs[0].id);
					}
				});
			}
		},
		getAllOptionals: function(formId, onlyHidden) {
			var labels = new Array();
			if(onlyHidden) {
				var optionals = dojo.query('.formElCellOptional.hidden', formId); 
			} else {
				var optionals = dojo.query('.formElCellOptional', formId);
			}
			//console.log(optionals);
			optionals.forEach(function(cell){
				var inputs = dojo.query('.formElOptional .dijitInputContainer input', cell);
				var labelEls = dojo.query('label', cell);
				labels.push({
					name: labelEls[0].innerHTML, 
					optId: dojo.attr(inputs[0],'id')});
			});
			//console.log(labels);
			return labels;
		},
		showElement: function(elementId) {
			if(!elementId) { console.log("Couldn't find element " + elementId); return;}
			// hide yourself first
			//Forms.hideElement(elementId);
			//console.log("Show element " + elementId);
			//we must show a dropdown with all hidden labels for the user to select from, and the coresponding input id
			var parent = dijit.byId(elementId).domNode.parentNode;
			// check for plus/minus images and add them if neccessary
			if(dojo.query('.plusSign', parent).length < 1) {
				var plusImg = dojo.create('IMG', {'class': 'plusSign', 'src': '/images/btn/green-plus.png'}, parent, 'last');
				dojo.connect(plusImg, 'onclick', null, function() {
					// get the next optional id
					Forms.showNextElement(elementId);
				});
			}
			if(dojo.query('.minusSign', parent).length < 1) {
				var minusImg = dojo.create('IMG', {'class': 'minusSign', 'src': '/images/btn/red-minus.png'}, parent, 'last');
				dojo.connect(minusImg, 'onclick', null, function() {Forms.hideElement(elementId);});
			}
			// replace the label with a dropdown
			// get the label and hide it first
			var label = dojo.query('label', parent)[0];
            if (!Forms.showLabels) {
    			dojo.style(label, 'display', 'none');
    			
    			var selectorDijit = Forms.getOptionalSelector(elementId, parent);
    			if(selectorDijit) {
    				selectorDijit.setValue(elementId);
    			}
            }
			dojo.removeClass(parent, 'hidden');            
            dojo.query('.answerTd', parent.parentNode).removeClass('hidden');

			dojo.query('.formElCellOptional:not(.hidden) .minusSign').forEach(function(node, index, arr){
				if (index == 0 && arr.length == 1)
					dojo.style(node, 'display', 'none');
				else
					dojo.style(node, 'display', '');
			});
		}, 
		showNextElement: function(elementId) {
			//console.log('Show next element for ' + elementId);
			var parentForm = getForm(dojo.byId(elementId));
			// get next available optional
			var availableOptionalElements = dojo.query('.formElCellOptional.hidden div.formElOptional .dijitInputContainer input', parentForm);
			//console.log(availableOptionalElements);
			if(availableOptionalElements.length > 0) {
				Forms.showElement(dojo.attr(availableOptionalElements[0], 'id'));
			}
			
		},
		hideElement: function(elementId) {
			//console.log("Hide element " + elementId);
			dijit.byId(elementId).setValue('');
			var parent = dijit.byId(elementId).domNode.parentNode;
			dojo.addClass(parent, 'hidden');
            dojo.query('.answerTd', parent.parentNode).addClass('hidden');
            checkbox = dojo.query("[id^=additional_answer_ck]", parent.parentNode)[0];
            if (checkbox)
                checkboxWidget = dijit.byId(checkbox.id);                        
            if (checkbox && checkboxWidget && checkboxWidget.checked){                
                checkbox.click(); 
            }
			dojo.query('.formElCellOptional:not(.hidden) .minusSign').forEach(function(node, index, arr){
				if (index == 0 && arr.length == 1)
					dojo.style(node, 'display', 'none');
				else
					dojo.style(node, 'display', '');
			});
		},
		getOptionalSelector: function(elementId, elementParent) {
			// check for select element and create one if neccessary
			var selector = null;
			
			var selectorList = dojo.query('.optionalSelector', elementParent);
			if(selectorList.length < 1) {
				var parentForm = getForm(dojo.byId(elementId));
				var optionals = Forms.getAllOptionals(dojo.attr(parentForm,'id'));
				//console.log(optionals);
				
				var selectorId =  'selector_'+elementId;
				var selectorInput = dojo.create('INPUT', {'id' : selectorId}, elementParent, 'first');
				var optionsStore = new dojo.data.ItemFileWriteStore({data: {identifier: 'optId', label: 'name', items:optionals}});
				selector = new dijit.form.FilteringSelect({
					'class': 'optionalSelector', 
					store: optionsStore,
					value: elementId,
					onChange: function(newValue) {
						//console.log(newValue);
						Forms.hideElement(elementId);
						Forms.showElement(newValue);
						value = newValue;
					}
				}, 
				selectorId);
				//dojo.place(selector.domNode,parent, 'first');
			} else {
				selector = dijit.byNode(selectorList[0]);
			}
			// return the selector element
			return selector;
			
		}
};


var MergeFieldTable = {
	clearText: function(elemId){

	    var oe = dojo.byId(elemId);
	    if(!oe.value) return;
	    om = oe.value.valueOf();
	    om = strip(om.replace(/'/g, '"').toLowerCase());

	    if(typeof htmlContentElementId != 'undefined') {
		fck = FCKeditorAPI.GetInstance(htmlContentElementId);
		am = fck.EditorDocument.body.innerHTML.valueOf();
		am = strip(am.replace(/'/g, '"').toLowerCase());

		if(om == am){
		    
		    fck.Events.AttachEvent('OnFocus', function(){
			if(once == true){
			    fck.EditorDocument.body.innerHTML = '';
			    once = false;
			}
		    });
		}
	    }
	    
	},
	insertHtmlAndText: function(elemId){
		var oe = dojo.byId(elemId);
		if(!oe.value) return;
		
		// get the 2 content objects(html and text)
		// 2 variables must be declared with the ids for the 2 html elements 
		if(typeof htmlContentElementId != 'undefined') {
			// check for elementParents and their visibility
			var doAppend1 = true;
			if(typeof htmlContentElementParentId != 'undefined') {
				if(dojo.style(htmlContentElementParentId, 'display') == 'none')  doAppend1 = false;
			}
			if(doAppend1) {
				var oEditor = FCKeditorAPI.GetInstance(htmlContentElementId);
				oEditor.InsertHtml(oe.value);
			}
		}
		
		if(typeof textContentElementId != 'undefined') {
			var doAppend2 = true;
			if(typeof textContentElementParentId != 'undefined') {
				if(dojo.style(textContentElementParentId, 'display') == 'none')  doAppend2 = false;
			}
			if(doAppend2) {
				var textElem = dijit.byId(textContentElementId);
				textElem.setValue(textElem.getValue()+' '+oe.value);
			}
		}	
	},	 
	setTextEditorFocus: function (obj){		
		node = obj.domNode;								
		if (textFocusParam){
			node.value = "";
			textFocusParam = false;
		} else
			return;		
	},
	setFCKEditorFocus: function(){
		if (htmlFocusParam){
			fck = FCKeditorAPI.GetInstance('defaultemail_content');
			fck.Events.AttachEvent('OnFocus', function(){				
				fck.SetHTML('asdf');
			});
			htmlFocusParam = false;
		} else return;
	}
};

