dojo.require("dojo.html.*");
dojo.require("dojo.event.*");
dojo.require("dojo.io.*");
dojo.require("dojo.widget.*");
ajaxHandler = {
	// 1
	hijackClassName : "formsubmitter",
	// 2
	initialize : function() {
		this.hijackAllFormSubmitNodes();
	},
	// 3
	hijackAllFormSubmitNodes : function() {
		dojo.debug("Connecting to all elements with class "
				+ ajaxHandler.hijackClassName);
		var elements = dojo.html
				.getElementsByClass(ajaxHandler.hijackClassName);
		for (var i = 0; i < elements.length; i++) {	
		//alert('Node registered:' + elements[i].id);	  
			this.hijackNode(elements[i]);
		}
	},
	// 4
	hijackNode : function(node) {
		dojo.debug("Hijacking node");
		dojo.debug(node);
		if (node.isHijacked) {
			dojo.debug("Node is already hijacked - ignoring");
			return;
		}
		node.isHijacked = true;
		// Create object with common params for io.bind call
		var _this = this;
		var bindParams = {
			headers : {
				"Accept" : "application/json"
			},
			mimetype : "application/json",
			load : function(type, data, evt) {
				_this.handleResponse(data, evt, node);
			},
			error : function(type, evt) {
				_this.handleError(type, evt);
			},
			timeout : function(type, evt) {
				_this.handleError(type, evt);
			}
		};

		// end function
		if (node.nodeName == "INPUT" && node.name == "dummyElem") {
				//alert('dummy elem registered');
				// --start--dojo.event.connect----			
				dojo.event.connect(node, "onclick", function(evt) {
				var submitNode = document.getElementById("submitButton");
				evt.preventDefault();
				// Get parent form node for this input node
				var formNode = dojo.html.getParentByType(node, "FORM");
				var radio = document.getElementById('inStorePickUpRadio');
					    if(radio== null){ 
				formNode.action = "./storeLocatorHome.jsp?relStore=t";	
					             }
				// Create content object with the name/value pair of the submit
				// button
				// that's been clicked dojo.io.bind doesn't send the value of
				// submit
				// buttons when serializing the form as it doesn't know which
				// one
				// has
				// been clicked. Server side FormHandlers need this data to
				// invoke
				// the
				// correct formHandler method.
				var content = {};
				content[submitNode.name] = submitNode.value;
				dojo.debug("Form clicked - submitting form");
				dojo.debug(formNode);
				// Add the form node and the submit button name/value to the
				// io.bind
				// params
				dojo.lang.mixin(bindParams, {
					formNode : formNode,
					content : content
				});
				
				dojo.io.bind(bindParams);
			}

			);
		}

		else if (node.nodeName == "SELECT" && node.id == "provinceDD") {
			//alert('provinceDD elem registered');			
			// --start--dojo.event.connect----
			dojo.event.connect(node, "onchange", function(evt) {				
				var submitNode = document.getElementById("cityListButton");

				evt.preventDefault();
				// Get parent form node for this input node
                
				var formNode = dojo.html.getParentByType(node, "FORM");
				var radio = document.getElementById('inStorePickUpRadio');
				    if(radio== null){ 
				formNode.action = "./storeLocatorHome.jsp?relStore=t";	
					             }
				// Create content object with the name/value pair of the submit button
				var content = {};
				content[submitNode.name] = submitNode.value;
				dojo.debug("Form clicked - submitting form");
				dojo.debug(formNode);
				// Add the form node and the submit button name/value to the io.bind params
				dojo.lang.mixin(bindParams, {
					formNode : formNode,
					content : content
				});
				// --end--dojo.event.connect----
				dojo.io.bind(bindParams);
			}

			);
		}

		// stop here
		else {
			dojo.debug("Node is not a form submit - ignoring");
		}
	},
	handleResponse : function(data, evt, node) {
	//alert('000000000000000000');
		this.enableNode(node);
		if (node.nodeName == "SELECT" && node.id == "provinceDD") {	
		//alert('handleResponse provinceDD');
		 this.clearInStorePickUpDiv();   		
		 var cityDD = document.getElementById('cityDD');
		 
		// var cityDD = new dijit.form.ComboBox(cityDDNode);
		 
		// cityDD.reset();
		 
		 /*alert('options length:'+cityDD.options.length);
		 while(cityDD.options.length > 1){ 
		 	cityDD.options.remove(1); 
		 	 alert('options lengthzdfdf:'+cityDD.options.length);
		  }*/
		     
			if(cityDD!=null && cityDD.options!='undefined' && cityDD.options!=null)
			{
               var varLength = cityDD.options.length;				
				while(cityDD.options.length > 1)
				{
					cityDD.remove(1) ;
				}			
           }               
		 
		 if(data.cityList != null){ 		 
			 for(g=0; g < data.cityList.length;g++){ 
				 var cityValue = data.cityList[g].replace(/^\s+|\s+$/g,"");
			   if(cityValue!="" && cityValue!=null && cityValue!="null" ){
				newOption = new Option(cityValue); 
			  	cityDD.options.add(newOption);
				 }
			  }
		  }
		  
			//alert('data.cityList len:' + data.cityList.length);
			//alert('data.cityList[0]' + data.cityList[0]);
		} else if(node.nodeName == "INPUT" && node.name == "dummyElem"){
			//alert('dummy elem -handleResponse'); 
			var currMarker = gmarkers[currMarkerPos];
			//Sets Centre for the selected store
			map.panTo(currMarker.getLatLng());
			var addr1 = data.address1.replace("&amp;#39;","'");
			    addr1 = addr1.replace("&amp;amp;","&");
			var storeLocation = addr1;				
		    var addr2 ='';
		    if(data.address2 == null || data.address2.length < 1){
		    	//alert('data.address2 is null:>' + data.address2 + '<');
		    	data.address2='';		    	
		    }else{
		    	//alert('data.address2 is not null:>' + data.address2 + '<');
				addr2  = data.address2.replace("&amp;amp;","&");
                 addr2 = addr2.replace("&amp;#39;","'");
		    	storeLocation = storeLocation + ', ' + addr2; 
				
		    } 
		    
		    storeLocation += ', ' + data.storeCity + ', ' + data.province + ', ' + data.postalcode;
		    
		    //get the locale
			var	locale = document.getElementById('usrlocale').value;
		    
		    // Labels For Store window
		    
		    var phoneLabel = '';
		    var faxLabel = '';
		    var tollFreeLabel = '';
		    var emailLabel = '';
		    var openedSiceLabel = '';
		 
	 
		    if(data.phoneNumber!='' && data.phoneNumber!=null){
		    	phoneLabel=phoneTxt + data.phoneNumber+'<br>';	
		 
		    }		    
		    if(data.faxNumber!=''&& data.faxNumber!=null){
		    	faxLabel=faxTxt + data.faxNumber+'<br>';
		 
		    }		    
		    if(data.tollFree!='' && data.tollFree!=null){
		    	tollFreeLabel=tollFreeTxt + data.tollFree+'<br>';
		    
		    }	
		    if(data.emailAddress!='' && data.emailAddress!=null){
		    	emailLabel= emailTxt +  '<a style="text-decoration:underline" href="Mailto:' + data.emailAddress + '"'+'>' + data.emailAddress + '</a>';
		    }
		    if(data.openedSincedate!='' && data.openedSincedate!=null){
		    	openedSiceLabel=openedSiceTxt + data.openedSincedate;		
		    }
		    
		    //reset the div
		    var storeDetailsDiv = $('#storeDetailsDiv');
			var storeName  = storeDetailsDiv.find('#storeName');
			var storeNameType   = 	storeDetailsDiv.find('#storeNameType');
			var storeImgDiv = storeDetailsDiv.find('#storeImgDiv');
			storeImgDiv.html('<img src ="' + data.storeImage + '" align ="left" width="130" height="95" style="margin: 2px 10px 5px 0;" />');
			var dataStroeName = data.storeName.replace("&amp;#39;","'");
			storeName.html(dataStroeName + '<br />');
			storeNameType.html(data.storeType);			
			var addressDiv	= storeDetailsDiv.find('#addressDiv');			
			addressDiv.html(addr1 + ' '  + addr2
									+ '<br>'
									+ data.storeCity + ', ' + data.province + ' ' + data.postalcode
									+ '<br>'
									+ phoneLabel									 
									+ faxLabel									 
									+ tollFreeLabel);				
			var emailDiv	= storeDetailsDiv.find('#emailDiv');
 	        emailDiv.html(emailLabel);	
			var dateDiv	= storeDetailsDiv.find('#dateDiv');
			dateDiv.html(openedSiceLabel);				
			var bussHoursDiv	= storeDetailsDiv.find('#bussHoursDiv');
			bussHoursDiv.html(this.replaceESCSeq(data.hoursofBusiness));
			var toHereDiv	= storeDetailsDiv.find('#toHereDiv');
			toHereDiv.html(URLencode('<a  style="text-decoration:underline" href="http://maps.google.com/maps?hl=' + locale + '&f=d&daddr='+ storeLocation + '&ie=UTF8&z=10" target="_blank">'+toHereTxt+'</a>'));
			var fromHereDiv	= storeDetailsDiv.find('#fromHereDiv');
			fromHereDiv.html(URLencode('<a  style="text-decoration:underline" href="http://maps.google.com/maps?hl=' + locale + '&f=d&saddr='+ storeLocation + '&ie=UTF8&z=10" target="_blank">'+fromHereTxt+'</a>'));
			
			currMarker.openInfoWindowHtml('<div  style="width: 332px; height: 300px;">'+storeDetailsDiv.html()+'</div>');
			}			
	},
	handleError : function(type, evt) {
		alert("Error: " + evt.message);
	},
	enableNode : function(node) {
		// place holder for enable node
	},
	replaceESCSeq : function(str){
	  if(str!=null){
			var regExpLT = new RegExp("&amp;lt;", "gi");
			var regExpGT = new RegExp("&amp;gt;", "gi");
			var regExpSP = new RegExp(" ", "gi");
			str=str.replace(regExpLT,'<');
			str=str.replace(regExpGT,'>');			
			str=str.replace(regExpSP,'&nbsp;');
		}
		
		return str;
	},
	//To clear instore pick up location section
	clearInStorePickUpDiv : function(){
		var inStoreDiv = document.getElementById('inStorePckUpResultsDiv');
		if(inStoreDiv != null){
			inStoreDiv.innerHTML = '';
		}
	}
}

