/**
main.js (0.75)
*/

id=0;
var pe;
var map;
var geocoder;
/////////////////
//MAPS CODE
////////////////
    function loadgeocoder() {
      if (GBrowserIsCompatible()) {
        geocoder = new GClientGeocoder();
      }
    }
	
   function selectStore(){
	   //alert("test");
	   var address = $('storeselect').value;
	   //alert(address);
       geocoder.getLatLng(address, function(latlng) {
	   if (!latlng) {
		    //fix for ie6
			 geocoder.getLocations(address, function(response){
				// Retrieve the object
      			place = response.Placemark[0];
      			// Retrieve the latitude and longitude
      			point = new GLatLng(place.Point.coordinates[1],
                          place.Point.coordinates[0]);										 
				if(!point){										 
		   			//alert(latlng);
	   				var answer = confirm("Your entry " + address + " seems to be invalid \n Press Ok to re-enter your postal code.  \n Press Cancel to continue to the website without location specific information.")
	   				if (answer){
						eraseCookie('tscpostal');
						return;
					}else{
						eraseCookie('tscpostal');
						window.location = "mainhome.php";
						return;
					}
				}else{
					//alert(point);
					latlng=point;
				}
			  });
	   }
	 	createCookie('tscpostal',address,360);
	   	createCookie('tsclat',latlng.lat(),360);
		createCookie('tsclng',latlng.lng(),360);
		window.location = "mainhome.php";
	   });
   }	
	
	
   function validatePostal(){
	   //alert("test");
	   var address = $('postal').value;
       geocoder.getLatLng(address, function(latlng) {
	   if (!latlng) {
		    //fix for ie6
			 geocoder.getLocations(address, function(response){
				// Retrieve the object
      			place = response.Placemark[0];
      			// Retrieve the latitude and longitude
      			point = new GLatLng(place.Point.coordinates[1],
                          place.Point.coordinates[0]);										 
				if(!point){										 
		   			//alert(latlng);
	   				var answer = confirm("Your entry " + address + " seems to be invalid \n Press Ok to re-enter your postal code.  \n Press Cancel to continue to the website without location specific information.")
	   				if (answer){
						eraseCookie('tscpostal');
						return;
					}else{
						eraseCookie('tscpostal');
						window.location = "mainhome.php";
						return;
					}
				}else{
					//alert(point);
					latlng=point;
				}
			  });
	   }
	 	createCookie('tscpostal',address,360);
	   	createCookie('tsclat',latlng.lat(),360);
		createCookie('tsclng',latlng.lng(),360);
		window.location = "mainhome.php";
	   });
   }

   function validatePostal2(){
	   //alert("test");
	   var address = $('postal').value;
       geocoder.getLatLng(address, function(latlng) {
	   if (!latlng) {
		    //fix for ie6
			 geocoder.getLocations(address, function(response){
				// Retrieve the object
      			place = response.Placemark[0];
      			// Retrieve the latitude and longitude
      			point = new GLatLng(place.Point.coordinates[1],
                          place.Point.coordinates[0]);										 
				if(!point){										 
		   			//alert(latlng);
	   				alert("Your entry " + address + " seems to be invalid \n Please re-enter your postal code.");
	   				eraseCookie('tscpostal');
					return;
				}else{
					latlng=point;
				}
			  });
	   }
	 	createCookie('tscpostal',address,360);
	   	createCookie('tsclat',latlng.lat(),360);
		createCookie('tsclng',latlng.lng(),360);
		getPostalandClosestStore();
	   });
   }



   function getPostalandClosestStore() {
	 loadgeocoder();  
     var ll = readCookie('tscpostal');
	 if(!ll){PostalEntry();};
	 geocoder.getLatLng(ll, function(latlng) {
	 if (!latlng) {	
	 	PostalEntry(); 
	 }else{
        //alert(latlng);
	    ClosestStore(latlng);	 
     }
	});
   }
   function initializeIndex() {
	 getData('storeselector','storeSelector',0,'views/storeSelector.php');  
   }

   function ClosestStore(center) {
	 getData('ClosestStore','closeststore',center.lat()+','+center.lng(),'views/closeststore.php');  
   }
   
   function PostalEntry() {
	 getData('PostalEntry','closeststore',0,'views/postalentry.php');  
   }
   function GetStoreLocator(iValue) {
	 getData('Locator','maincontent_left',iValue,'views/storelocator.php');
   }   
   function GetLocalStore() {
	 getData('Locator','maincontent_left',0,'views/localstorelocator.php');
   }
   function SelectLocalStore(iValue) {
	 getData('Locator','maincontent_left',iValue,'views/localstorelocator.php');
   }   
   function SelectStoreLocator(iValue) {
	 getData('Locator','maincontent_left',iValue,'views/storelocator.php');
   }

   function LocalStoreLocator(lat,lng){
 	 loadgeocoder();  
        map = new GMap2(document.getElementById('map'));
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(42.95, -81.158379), 5);
		
        map.clearOverlays();

        var bounds = new GLatLngBounds();
        var point = new GLatLng(lat,lng);
    	var tscicon= new GIcon();	
	  	tscicon.image = "http://www.tscstores.com/images/tsc_icon.png";
		tscicon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
	  	tscicon.iconSize = new GSize(15,14);
		tscicon.shadowSize = new GSize(30,14);
		tscicon.iconAnchor = new GPoint(6,14);
		tscicon.infoWindowAnchor = new GPoint(5,1);
			
			// Set up our GMarkerOptions object literal
		markerOptions = { icon:tscicon };
		 
	    var marker = new GMarker(point, markerOptions);
		
		map.addOverlay(marker);
	   	bounds.extend(point);
	
	   var zoomlevel = map.getBoundsZoomLevel(bounds);
	   if(zoomlevel>13){zoomlevel=13}
       map.setCenter(bounds.getCenter(), zoomlevel);
	
	   openSlow('#maincontent_left');   
   }   
   
   function StoreLocator(lat,lng){
 	 loadgeocoder();  
	 var radius = 100000;
     var searchUrl = 'getRadialStores.php?lat=' + lat + '&lng=' + lng + '&radius=' + radius;
	 //alert(searchUrl);
 	 GetStoreMap(searchUrl);
   }
   
   function StoreLocatorAmy(lat,lng){
 	 loadgeocoder();  
	 var radius = 100000;
     var searchUrl = '../getRadialStores.php?lat=' + lat + '&lng=' + lng + '&radius=' + radius;
	 //alert(searchUrl);
 	 GetStoreMap(searchUrl);
   }
   
   
   function GetStoreMap(searchUrl){
        map = new GMap2(document.getElementById('map'));
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(42.95, -81.158379), 5);
		searchLocationsNear(searchUrl);
		openSlow('#maincontent_left');
   }
   
   
   
   
   function getWeather(wnCode) {
	 getData('WeatherStore','storeweather',wnCode,'views/weather.php');  
   }   


   function searchLocationsNear(searchUrl) {
     //var radius = 100000;
     //var searchUrl = 'getRadialStores.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
     GDownloadUrl(searchUrl, function(data) {
       var xml = GXml.parse(data);
       var markers = xml.documentElement.getElementsByTagName('marker');
       map.clearOverlays();

       var sidebar = document.getElementById('sidebar');
       sidebar.innerHTML = '';
       if (markers.length == 0) {
         sidebar.innerHTML = 'No results found.';
         map.setCenter(new GLatLng(40, -100), 4);
         return;
       }

       var bounds = new GLatLngBounds();
       for (var i = 0; i < markers.length; i++) {
         var name = markers[i].getAttribute('name');
         var address = markers[i].getAttribute('address');
		 var diventry = markers[i].getAttribute('city')+ ' ,' +markers[i].getAttribute('prov')+' '+markers[i].getAttribute('postal')+ '<br/>'+markers[i].getAttribute('phone');
         var distance = parseFloat(markers[i].getAttribute('distance'));
         var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
                                  parseFloat(markers[i].getAttribute('lng')));
 
 	   	   var tscicon= new GIcon();	
	  	   tscicon.image = "http://www.tscstores.com/images/tsc_icon.png";
		   tscicon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
	  	   tscicon.iconSize = new GSize(15,14);
		   tscicon.shadowSize = new GSize(30,14);
		   
		   tscicon.iconAnchor = new GPoint(6,14);
		   tscicon.infoWindowAnchor = new GPoint(5,1);
			
			// Set up our GMarkerOptions object literal
		markerOptions = { icon:tscicon };
		
		//SET UP HTML FOR POPUP AND SIDEBAR
		var storehtml= storeHTML(markers[i]);
		var storeid=markers[i].getAttribute('id');
	    //ADD MARKER
		var marker = createMarker(point, markerOptions, storehtml, storeid);
		map.addOverlay(marker);
				
		 if(i<5){ 
         	var sidebarEntry = createSidebarEntry(marker, storehtml, storeid);
         	sidebar.appendChild(sidebarEntry);
         	bounds.extend(point);
		 }
	   }
	   var zoomlevel = map.getBoundsZoomLevel(bounds);
	   if(zoomlevel>13){zoomlevel=13}
       map.setCenter(bounds.getCenter(), zoomlevel);
     });
   }
   
   function storeHTML(XMLAttributes){
     var html = '<b>'+XMLAttributes.getAttribute('name') + '</b> <br/>' + XMLAttributes.getAttribute('address') +'<br/>';
	 html+=XMLAttributes.getAttribute('city')+ ', ' +XMLAttributes.getAttribute('prov')+' '+XMLAttributes.getAttribute('postal')+ '<br/>';
	 html+='Manager: '+ XMLAttributes.getAttribute('manager')+'<br>';
	 html+=XMLAttributes.getAttribute('phone');
	 
	 return html;
   }	 

    function createMarker(point, markerOptions, html, storeid) {
	  var marker = new GMarker(point, markerOptions);
  
	  GEvent.addListener(marker, 'click', function() {
        //marker.openInfoWindowHtml(html);
		SelectLocalStore(storeid);
      });
      return marker;
    }

    function createSidebarEntry(marker, html, storeid) {
      var div = document.createElement('div');
      //var html = '<b>' + name + '</b> (' + distance.toFixed(1) + ' km)<br/>' + address +'<br/>' + diventry;
	  div.innerHTML = html;
      div.style.cursor = 'pointer';
      div.style.marginBottom = '5px'; 
      GEvent.addDomListener(div, 'click', function() {
      	//  GEvent.trigger(marker, 'click');
	  	SelectLocalStore(storeid);
      });
      GEvent.addDomListener(div, 'mouseover', function() {
        div.style.backgroundColor = '#eee';
      });
      GEvent.addDomListener(div, 'mouseout', function() {
        div.style.backgroundColor = '#fff';
      });
      return div;
    }

//////////////////////////
//CORE CALLING FUNCTIONS
//////////////////////////
 function getData(iAction,iTarget,iValue,iurl){
 	$(iTarget).innerHTML='<img src="images/ajax-loader.gif">';
	//var url='../scripts/adminEditorScript.php';
	var rand=Math.random(9999);
	var pars='iValue='+iValue+'&iAction='+iAction+'&iTarget='+iTarget+'&rand='+rand;
	var myAjax=new Ajax.Updater(iTarget,iurl,{method: 'post', parameters: pars, evalScripts:true});
	//jQuery('#'+iTarget).hide();
	//openSlow('#'+iTarget);
	//if(document.location.hash){
	//	document.location.hash='';
	//}
}
 
 function submitform(iValue,iAction,iForm,iTarget,iurl){
 	
	//var url='../scripts/mvc_admin_scripts.php';
	var rand=Math.random(9999);
	var pars=$(iForm).serialize()+'&iValue='+iValue+'&iAction='+iAction+'&rand='+rand;
	$(iTarget).innerHTML='<img src="images/ajax-loader.gif">';
	var myAjax=new Ajax.Updater(iTarget,iurl,{method: 'post', parameters: pars , evalScripts:true});
	//alert(iurl);
}

// AC - 111108 (changed effect)
 function closeSlow(target){
	jQuery(target).animate({ height: 'hide', opacity: 'hide' }, 500);
 }
// AC - 111108 (changed effect)
 function openSlow(target){
	jQuery(target).animate({ height: 'show', opacity: 'show' }, 500);
	//jQuery(target).show("slow");

 } 
/////////////////////////////
//LOGIN
////////////////////////////

 function loadleftNav(){
	 //alert('test');
	 getData('get_left_nav','leftNav',0,"views/left_nav.php");
	 getData('get_main_nav','mainnav',0,"views/main_nav.php");
	 getData('get_main_content','rightNav',0,"views/right_nav.php");
	 getData('get_boxes','mainbottom',0,"views/bottom_4.php");
	 getData('get_main_content','maincontent_left',0,"views/homepage_content.php");
	 resetRightNav();
	
	
 }
 function loadleftNavTest(){
	 //alert('test');
	 getData('get_left_nav','leftNav',0,"views/test/left_nav.php");
	 getData('get_main_nav','mainnav',0,"views/test/main_nav.php");
	 getData('get_main_content','rightNav',0,"views/right_nav.php");
	 getData('get_boxes','mainbottom',0,"views/bottom_4.php");
	 getData('get_main_content','maincontent_left',0,"views/homepage_content.php");
	 resetRightNav();

 }
 
 function resetRightNav(){
	 openSlow('#main_nav_right');
	 closeSlow('#comm_nav1');
	 closeSlow('#comm_nav2'); 
 }
 function loadOFA(){
	 getData('get_main_content','maincontent_left',0,"views/ofa_release.php");
	 resetRightNav();
 }
 
 function loadTSCofferform(){
	 getData('get_main_content','maincontent_left',0,"views/tscoffers.php");
	 resetRightNav();
 }
  function loadTSCofferformTest(){
	 getData('get_main_content','maincontent_left',0,"views/test/tscoffers.php");
	 resetRightNav();
 }
 
 function loadExtendedWarranty(){
	 getData('get_main_content','maincontent_left',0,"views/warranty.php");
	 resetRightNav();
 } 
 function loadCommercialRewards(){
	 getData('get_main_content','maincontent_left',0,"views/commercialrewards.php");
	 closeSlow('#main_nav_right');
	 closeSlow('#comm_nav1');
	 openSlow('#comm_nav2');
 } 
 function loadCommercial(){
	 getData('get_main_content','maincontent_left',0,"views/commericalaccount.php");
	 closeSlow('#main_nav_right');
	 openSlow('#comm_nav1');
	 closeSlow('#comm_nav2');
}
  function loadAbout(){
	 getData('get_main_content','maincontent_left',0,"views/aboutus.php");
	 resetRightNav();
 }
  function loadCredit(){
	 getData('get_main_content','maincontent_left',0,"views/creditcard.php");
	 resetRightNav();
 } 
   function loadHome(){
	 getData('get_main_content','maincontent_left',0,"views/homepage_content.php");
	 resetRightNav();
 }
 function loadDept(iValue){
	 getData('get_main_content','maincontent_left',0,"views/"+iValue+".php");
	 resetRightNav();
 }
 function loadUC(){
	 getData('get_main_content','maincontent_left',0,"views/UnderConstruction.php");
	 resetRightNav();
 } 

 
 function getGiftCard(){
	 getData('get_main_content','maincontent_left',0,"views/giftcard.php");
	 resetRightNav();
 } 
 
 function getUnderConstruction(){
	 getData('get_uc','maincontent_left',0,"views/construction.php");
	 resetRightNav();
 } 
 
 
 function getBrands(){
	 getData('get_main_content','brands',0,"views/brands.php");
	 resetRightNav();
 }
 function getNews(){
	 getData('get_main_content','headlines',0,"views/news.php");
	 resetRightNav();
 }
  function getFarmNews(){
	 getData('get_main_content','maincontent_left',0,"views/newspage.php");
	 resetRightNav();
 }
  function loadContact(){
	 getData('get_main_content','maincontent_left',0,"views/contactus.php");
	 resetRightNav();
 }
  function loadPrivacy(){
	 getData('get_main_content','maincontent_left',0,"views/privacy.php");
	 resetRightNav();
 } 
 
 function getBoxFlyer(){
	 zegapi_viewer('http://zegapi.com/view/?book_name=tsc12cboxingday');
 } 
 
 function getFlyer(campaign){
	 if(campaign==undefined){
	 	pageflip3d_viewer('http://tscstores.com/stage/s2flyer.php?cpg=website');
	 }else{
		pageflip3d_viewer('http://tscstores.com/stage/s2flyer.php?cpg='+campaign);
	 }
 }
////////COOKIE SCRIPTS
// cookie scripts//
 function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}


function gosave()
	{
	  err="";
	
	 
	   if(document.future.firstname.value=="")
	{
		 err+="First Name\n\r";
		
	}
	
	   if(document.future.lastname.value=="")
	{
		 err+="Last Name\n\r";
	}
	
	 if(document.future.email.value=="")
	{
		 err+="Email\n\r";
	}
	
/*	
	if((document.future.password.value==""))
	{
		 err+="Password\n\r";
	}
	
	if((document.future.cpassword.value==""))
	{
		err+="Confirm password\n\r";
	}
	
	if(document.future.cpassword.value!=document.future.password.value)
	{
		 err+="Confirm Password  should match with the Password\n\r";
	}
	
		
	
	  if(document.future.question.value=="")
	{
		 err+=" Question\n\r";
	}
*/	  
	
	
	
	
	
	if(err != "")
	{
		alert("Please provide values for:\n\r"+err);
		document.future.firstname.focus();
	}
	else
	{
		action='http://app.icontact.com/icp/signup.php';
		params='redirect=http://www.tscstores.com/emailer/success.php?callback=?';
		params+='&errorredirect=http://www.tscstores.com/emailer/failure.php?callback=?';
		params+='&fields_email='+document.future.email.value;
      	params+='&fields_fname='+document.future.firstname.value;
     	params+='&fields_lname='+document.future.lastname.value;
      	params+='&listid=55213';
    	params+='&specialid:55213=4BNN';
		params+='&clientid=470212';
    	params+='&formid=3352';
    	params+='&reallistid=1';
    	params+='&doubleopt=0';
		params+='&Submit=Submit&f=json&callback=?';
		
		iValue='';
		//alert("Please provide values for:");
		jQuery.getJSON("http://app.icontact.com/icp/signup.php?"+params,
   		function(result){
			//alert(result.success);
      		iValue=result.success;
			submitform(iValue,'save_reg','future','maincontent_left','views/script_runner.php');
			//alert(iValue);
   		}
		);
		//submitform(iValue,iAction,iForm,iTarget,iurl);
	
	}
}

function gosave_test()
	{
	  err="";
	
	 
	   if(document.future.firstname.value=="")
	{
		 err+="First Name\n\r";
		
	}
	
	   if(document.future.lastname.value=="")
	{
		 err+="Last Name\n\r";
	}
	
	 if(document.future.email.value=="")
	{
		 err+="Email\n\r";
	}
	
/*	
	if((document.future.password.value==""))
	{
		 err+="Password\n\r";
	}
	
	if((document.future.cpassword.value==""))
	{
		err+="Confirm password\n\r";
	}
	
	if(document.future.cpassword.value!=document.future.password.value)
	{
		 err+="Confirm Password  should match with the Password\n\r";
	}
	
		
	
	  if(document.future.question.value=="")
	{
		 err+=" Question\n\r";
	}
*/	  
	
	
	
	
	
	if(err != "")
	{
		alert("Please provide values for:\n\r"+err);
		document.future.firstname.focus();
	}
	else
	{
		//submitform(iValue,iAction,iForm,iTarget,iurl);
	
		//SAVING FOR ICONTACT
		action='http://app.icontact.com/icp/signup.php';
		params='redirect=http://www.tscstores.com/emailer/success.php?callback=?';
		params+='&errorredirect=http://www.tscstores.com/emailer/failure.php?callback=?';
		params+='&fields_email='+document.future.email.value;
      	params+='&fields_fname='+document.future.firstname.value;
     	params+='&fields_lname='+document.future.lastname.value;
      	params+='&listid=55213';
    	params+='&specialid:55213=4BNN';
		params+='&clientid=470212';
    	params+='&formid=3352';
    	params+='&reallistid=1';
    	params+='&doubleopt=0';
		params+='&Submit=Submit&f=json&callback=?';
		
		iValue='';
		jQuery.getJSON("http://app.icontact.com/icp/signup.php?"+params,
   		function(result){
      		iValue=result.success;
   		}
		);
	}
}	
