var JDC = YAHOO.namespace("JDC");
var isEven = function(value) {if (value%2 == 0)	{return true;} return false; };
// Array.splice() - Remove or replace several elements and return any deleted elements

var arrsplice = function(arr, a, c ) {
  var i = 0, e = arguments, d = arr.copy(), f = a, l = arr.length;
  if( !c ) { c = l - a; }
  for( i; i < e.length - 2; i++ ) { arr[a + i] = e[i + 2]; }
  for( a; a < l - c; a++ ) { arr[a + e.length - 2] = d[a - c]; }
  arr.length -= c - e.length + 2;
  return d.slice( f, f + c );
 };

if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        }
    }
}

JDC.siteurl = "http://caringtouchdental.com";
JDC.siteurlS = "https://caringtouchdental.com";

window.onload = function() {

  // START UP THE GOOGLE MAPERATOR
  if (window.GBrowserIsCompatible && GBrowserIsCompatible() && (document.getElementById("google_map") || document.getElementById("google_map_small"))) 
  {
	var mapzoom = 0;
	var maptype = 1;
	var mapcon;

	if (document.getElementById("google_map")) {
		mapcon = document.getElementById("google_map");
		mapzoom = 16;
	} else if (document.getElementById("google_map_small")) {
		mapcon = document.getElementById("google_map_small");
		mapzoom = 15;
		maptype = 2;
	}

	var map = new GMap2(mapcon);
	map.setCenter(new GLatLng(41.995972, -87.748296), mapzoom);

	//add controls
	map.addControl(new GSmallMapControl());
	if (maptype == 1)
		map.addControl(new GMapTypeControl());

	// Create our "tiny" marker icon
	var JDCIcon = new GIcon(G_DEFAULT_ICON);
	JDCIcon.image = JDC.siteurl+"/style/default/img/jdcicon.png";
	JDCIcon.iconSize = new GSize(37, 40);
	JDCIcon.iconAnchor = new GPoint(25, 30);
	JDCIcon.infoWindowAnchor = new GPoint(25, 30);

	// Set up our GMarkerOptions object
	markerOptions = { icon:JDCIcon };

	//add marker
	var point = new GLatLng(41.995972, -87.748296);
	map.addOverlay(new GMarker(point,markerOptions));

	//display window
	map.addOverlay(createMarker(point));
  }

  initialize();

  if (document.getElementById('directions-adv'))
	  document.getElementById('directions-adv').style.display = 'none';
}

// THIS IS BAD, REMOVE ASAP

function initialize() {
	if (window.GBrowserIsCompatible && GBrowserIsCompatible()) {      
		map = new GMap2(document.getElementById("map_canvas"));
		if (document.getElementById("directions")) {
			gdir = new GDirections(map, document.getElementById("directions"));
			GEvent.addListener(gdir, "load", onGDirectionsLoad);
			GEvent.addListener(gdir, "error", handleErrors);

			//setDirections("", "", "en_US");
			map.setCenter(new GLatLng(41.995972, -87.748296), 16);

			//add controls
			map.addControl(new GSmallMapControl());
			map.addControl(new GMapTypeControl());
		}
	}
}

window.onunload = function() {
	if (window.gUnload)
		gUnload();
}

function createMarker(point) {
	var marker = new GMarker(point,markerOptions);
	GEvent.addListener(marker, "click", function(){
		marker.openInfoWindowHtml("<span style=\'font-size:1em\'><b>Caring Touch Dental</b><br />6314 N. Cicero Ave.<br />Chicago, Illinois 60646<br />(773) 736-7768</span>");
	});
	return marker;
}

function setDirections(fromAddress, toAddress, locale,mode) {
	
	var travelMode;

	switch (mode)
	{
		case 'DRIVING':travelMode = G_TRAVEL_MODE_DRIVING;break;
		case 'WALKING':travelMode = G_TRAVEL_MODE_WALKING;break;
	}

	gdir.load("from: " + fromAddress + " to: " + toAddress,
				{ "locale": locale,"travelMode":travelMode });
}

function handleErrors(){
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
   
	else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
		alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
	 
	else if (gdir.getStatus().code == G_GEO_BAD_KEY)
		alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
		alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	
	else alert("An unknown error occurred.");
}

function onGDirectionsLoad(){ 
  // Use this function to access information about the latest load()
  // results.

  // e.g.
  // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
  // and yada yada yada...
}

function switchdirections(type) {
	if (type == "simple") {
		document.getElementById("directions-adv").style.display = "none";
		document.getElementById("directions-simple").style.display = "block";
	}

	if (type == "adv") {
		document.getElementById("directions-simple").style.display = "none";
		document.getElementById("directions-adv").style.display = "block";
	}
}

function formGet(formname) {
	document.location.href=JDC.siteurl+"/forms/pdf/caringtouchdental_"+formname+".pdf";
}

function formFile(formid) {
	var h = self.innerHeight;
	var wloc = JDC.siteurlS+"/fileform/"+formid;

	if(!h)
		h = document.documentElement.clientHeight-document.body.clientHeight;

	window.open(wloc, "currentform","width=790,height="+h+",directories=no,titlebar=no,status=no,toolbar=no,menubar=no,location=no,address=no,resizable=no,scrollbars=yes");    
}

function printform() {
	if (!document.getElementById('formverify').checked)	{
		if (confirm("You have not confirmed the form has been filled out completely.  Continue printing?"))
			window.print();
	} else
		window.print();
}

function submitform(f) {
	document.getElementById('formsubmit').disabled = 'disabled';
	if (document.getElementById('formverify') && !document.getElementById('formverify').checked) {
		alert("Please make sure the form is filled out completely, then check the box above \nto verify you have completed the form.");
		document.getElementById('formsubmit').disabled = '';
		return false;
	} else if (document.getElementById('formemail') && document.getElementById('formemail').value == '' && !confirm("You will not be receiving email confirmation.  Is that ok?")) {
		document.getElementById('formsubmit').disabled = '';
		return false;
	} else
		return true;
}

function closeform() {
	//if (confirm("Thank you for your submission.  Close this window?")) {
		window.close();
		return true;
	//}
}

(function() { 
    var Dom = YAHOO.util.Dom, 
        Event = YAHOO.util.Event,
        Connect = YAHOO.util.Connect,
        JSON = YAHOO.lang.JSON,
		Cookie = YAHOO.util.Cookie;

	var searchDefault = "Search...";

	YAHOO.util.Get.script('src/connection.js');

	var cEvents = {};								//
													//
	if (JDC.cEvents)	{								//	This is only nJDCded because stupid javascript isn't
		cEvents.start = JDC.cEvents.start;			//  loading connection.js in time for JDC.cEvents to be
		cEvents.failure = JDC.cEvents.failure;		//  defined.  Especially since this is a function I can
		cEvents.complete = JDC.cEvents.complete;		//  call later.
	} else {
		cEvents.start = function(){};
		cEvents.failure = function(){};
		cEvents.complete = function(){};
	}

	// Load the session object into the client
	JDC.loadSession = function(){
		
		var sessionloader = Connect.asyncRequest('GET',"./?loadSession", {

			/*customevents:{ 
				onStart:JDC.cEvents.start,
				onFailure:JDC.cEvents.failure,
				onComplete:JDC.cEvents.complete
			},*/

			success: function(o) {
				response = null;
				
				try  { response = JSON.parse(o.responseText);}
				catch (e){window.alert("Error in parsing session response from server.");return;}

				if (response.error)
					window.alert(response.error);
				else
					JDC.session = response.session;
			},

			timeout: 1200
		});
	};

	JDC.submitContactForm = function(){

		var formError = false;
		Connect.setForm(JDC.contactForm);
		JDC.btnSubmitContact.disabled = 'disabled';

		// Validate form

		if (Dom.get('contact-name').value == '' || Dom.get('contact-email').value == '' || Dom.get('contact-issue').value == '') {
			window.alert("Please make sure all bolded items are filled out.");
			formError = true;
		}


		// Submit form 

		if (!formError) {

				var thanksPage = Dom.get('contact-thanks');
				var loadingPage = Dom.get('contact-loading');

				Dom.setStyle(loadingPage,'display','block');
				Dom.setStyle(JDC.contactForm,'display','none');
				
				var contactsubmit = Connect.asyncRequest('POST',"./?_goPostContactForm", {

					customevents:{ 
						onStart:JDC.cEvents.start,
						onFailure:JDC.cEvents.failure,
						onComplete:JDC.cEvents.complete
					},

					success: function(o) {

						response = null;

						if (o.responseText != '') {
							try {
								response = YAHOO.lang.JSON.parse(o.responseText);
							
							} catch (e) {
								Dom.setStyle(document.body,'cursor','default');
								window.alert("Error retrieving response from server.");
								Dom.setStyle(loadingPage,'display','none');
								Dom.setStyle(JDC.contactForm,'display','');
								return;
							}
						}					

						if (response && response.error)
							thanksPage.innerHTML = response.error;
						else
							thanksPage.innerHTML = "Thank you for your submission.  Dr. Poskozim will get back to you soon.  If you have provided your phone number, you may also receive a call.<br /><br />Thanks again.";

						window.setTimeout(function(){						
							Dom.setStyle(loadingPage,'display','none');
							Dom.setStyle(thanksPage,'display','block');
							Dom.setStyle(document.body,'cursor','default');
						},1000);
					},

					timeout: 10000
				});

			}

			JDC.btnSubmitContact.disabled = '';	
	};

	//JDC.loadSession();

	Event.onDOMReady(function() { 	

		Event.addListener('head-logo','click',function(){document.location.href = "/";});
		Event.addListener('head-logo','mouseover',function(){Dom.setStyle(this,'cursor','pointer');});
		Event.addListener('head-logo','mouseout',function(){Dom.setStyle(this,'cursor','default');});
		Event.addListener('head-name','click',function(){document.location.href = "/";});
		Event.addListener('head-name','mouseover',function(){Dom.setStyle(this,'cursor','pointer');});
		Event.addListener('head-name','mouseout',function(){Dom.setStyle(this,'cursor','default');});
		Event.addListener('head-sublogo','click',function(){document.location.href = "/";});
		Event.addListener('head-sublogo','mouseover',function(){Dom.setStyle(this,'cursor','pointer');});
		Event.addListener('head-sublogo','mouseout',function(){Dom.setStyle(this,'cursor','default');});

		JDC.mainMenu = new YAHOO.widget.MenuBar("site-menu", {autosubmenudisplay:true}); 

		function onSubmenuShow() { 

			var oIFrame,
				oElement,
				nOffsetWidth;

			// Keep the left-most submenu against the left edge of the browser viewport

			if (this.id == "yahoo") {
				YAHOO.util.Dom.setX(this.element, 0);
				oIFrame = this.iframe;            

				if (oIFrame) 
					YAHOO.util.Dom.setX(oIFrame, 0);
					
				this.cfg.setProperty("x", 0, true);
			}

			/*	Need to set the width for submenus of submenus in IE to prevent the mouseout 
				event from firing prematurely when the user mouses off of a MenuItem's 
				text node.	*/

			if ((this.id == "filemenu" || this.id == "editmenu") && YAHOO.env.ua.ie) {

				oElement = this.element;
				nOffsetWidth = oElement.offsetWidth;
                
			/*	Measuring the difference of the offsetWidth before and after
				setting the "width" style attribute allows us to compute the 
				about of padding and borders applied to the element, which in 
				turn allows us to set the "width" property correctly.      */
                        
				oElement.style.width = nOffsetWidth + "px";
				oElement.style.width = (nOffsetWidth - (oElement.offsetWidth - nOffsetWidth)) + "px";
			}
		}

		JDC.mainMenu.subscribe("show", onSubmenuShow);
		
		if (Dom.get('login')) {
			var resetPasswordButton = new YAHOO.widget.Button('link-resetpassword');
			var loginButton = new YAHOO.widget.Button('login-form-submit');

			Event.onAvailable(Dom.get('login-form'),function(){
			
				Dom.setStyle(this,'visibility','visible');
			
			});
		}

		if (Dom.get('form-contact'))
		{
			JDC.contactForm = Dom.get('form-contact');
			JDC.contactForm.onsubmit = function(){return false;};
			JDC.btnSubmitContact = Dom.get('contact-submit');

			Event.addListener(JDC.btnSubmitContact,'click',JDC.submitContactForm);
		}

		// Instantiate the User Settings Dialog 
		JDC.dlgTellFriend = new YAHOO.widget.Dialog("form-tellfriend", {
			width: "500px", 
			fixedcenter: true, 
			visible: false,
			modal: true,
			constraintoviewport: true, 
			buttons: [ { text:"Send Message", handler:function(){this.submit();}, isDefault:true }, 
					   { text:"Cancel", handler:function(){this.cancel();} } ] 
		});


		JDC.dlgTellFriend.beforeShowEvent.subscribe(function(){
		
			var f = Dom.get('tellfriend-form').getElementsByTagName('fieldset')[0];

			f.innerHTML = 	'<input type="hidden" name="bor" value="987654321" />'+
							'<div class="yui-gd">'+
							'	<div class="yui-u first">'+
							'		<label>Your Name:</label>'+
							'	</div>'+
							'	<div class="yui-u">'+
							'		<input id="tellfriend-name" name="name" value="" />'+
							'	</div>'+
							'</div>'+
							'<div class="yui-gd">'+
							'	<div class="yui-u first">'+
							'		<label>Your Email Address:</label>'+
							'	</div>'+
							'	<div class="yui-u">'+
							'		<input id="tellfriend-email" name="email" value="" />'+
							'	</div>'+
							'</div>'+
							'<hr />'+
							'<div class="yui-gd">'+
							'	<div class="yui-u first">'+
							'		<label>Recipient\'s Name:</label>'+
							'	</div>'+
							'	<div class="yui-u">'+
							'		<input id="tellfriend-toname" name="toname" value="" />'+
							'	</div>'+
							'</div>'+
							'<div class="yui-gd">'+
							'	<div class="yui-u first">'+
							'		<label>Recipient\'s Email Address:</label>'+
							'	</div>'+
							'	<div class="yui-u">'+
							'		<input id="tellfriend-toemail" name="toemail" value="" />'+
							'	</div>'+
							'</div>'+
							'<h4>Message:</h4>'+
							'<p>'+
							'	<i>I had a great experience at Caring Touch Dental, and I wanted to share that with you.  Dr. Joy Poskozim is personal, professional and knowledgeable.  Everyone at Caring Touch Dental truly do care about your dental health.</i>'+
							'</p>'+
							'<div class="yui-ga">'+
							'	<div class="yui-u">'+
							'		<h5>Personalize this message...</h5>'+
							'		<textarea id="tellfriend-pmsg" name="pmsg" style="width: 100%; height: 6em;" maxlength="250"></textarea>'+
							'	</div>'+
							'</div>';
		
			JDC.dlgTellFriend.render();
		});

		Event.addListener('button-tellfriend','click',function(e){
			
			/*var sinput = document.createElement('input');
			sinput.type = 'hidden';
			sinput.value = '987654321';
			sinput.name = 'bor';

			Dom.insertBefore(sinput,Dom.get('tellfriend-form').getElementsByTagName('fieldset')[0].firstChild);
			*/

			JDC.dlgTellFriend.show();
			Event.preventDefault(e);
		});

		Dom.setStyle('form-tellfriend','display','');

		var tellFriendSuccess = function(o) { 

			var response = null;
			//response = o.responseText.split("<!")[0]; 

			try  { 
				response = JSON.parse(o.responseText);
			} catch (e) {
				window.alert("We were unable to send your message.  Please try again later.");
				return;
			}

			if (response.errors){
				window.alert(response.errors);

			} else {
				window.alert("Thank you for your support!");
				Dom.get('tellfriend-form').reset();
			}
		}; 
		 
		var tellFriendFailure = function(o) { 
			window.alert("We were unable to send your message.  Please try again later."); 
		}; 
		 
		JDC.dlgTellFriend.callback = { success: tellFriendSuccess, 
										 failure: tellFriendFailure }; 	

		// Validate the entries in the form to require that all required fields are met
		JDC.dlgTellFriend.validate = function() {
			var data = this.getData();
			var hasError = false;

			if (data.name == "" || data.email == "" || data.toname == "" || data.toemail == "") {
				alert("Please ensure the first 4 fields are filled out.  We will not use this information for any marketing purposes.");
				hasError = true;
			}

			if (hasError) {
				return false;
			} else {
				return true;
			}
		};

		JDC.dlgTellFriend.render();

	});//--Event.onDomReady

})(); //--function()
