/**
 * @author dt.john
 */
$(document).ready(function(){
	window.validateForms = {};
	DOMUtilities.init();
	slideshowObj.init();
	FancyBox.init();
	DatePicker.init();
	CouponEmail.init();
	CouponPrint.init();
	FriendsTab.init();
	startForms.init();
	Appointment.init();
 });

$.extend({
	keys: function(obj){
		var a = [];
		$.each(obj, function(k){ a.push(k) });
		return a;
	}
});
/**
 * DOM Utilies Object for handling basic DOM actions
 * @author					Dave Shepard
 * @version					1.0
 * @required libraries:		JQuery 1.3.2 or later
 * 
 * Usage:
 *     $(document).ready(function(){
 *     		DOMUtilities.init();
 *     });
 *     
 * Can be initialized via the init(); method to apply to entire <body> or
 * a scope can be passed to limit the initialization to the child elements
 * of a particular element. Individual methods can als be called and passed
 * a scope.
 */
var DOMUtilities = {
	targetBlank: function(locality){
		// XHTML 1.0 Strict work around for external links
		$(locality+' a[rel*="external"]').attr("target","_blank");
	},
	inputAutoClear: function(locality){
		$(locality+' input.clearField').focus(function(){
			if(this.defaultValue == this.value) this.value='';
		}).blur(function(){
			if(this.value == '') this.value = this.defaultValue;
		});
	},
	imgRollover: function(locality){
		// Image roll-over setup
		$(locality+' img.rollOver, '+locality+' input[type="image"].rollOver')
			.mouseover(function(){
				if (this.src.indexOf("_i.") != -1) {
					this.src = this.src.replace("_i.", "_o.");
				}
			}).mouseout(function(){
				if (this.src.indexOf("_o.") != -1) {
					this.src = this.src.replace("_o.", "_i.");
				}
				if(this.src.indexOf("_a.")) {
					this.src = this.src.replace("_a.","_i.");
				}
			}).filter("input").mousedown(function(){
				this.src = this.src.replace("_o.","_a.");
			}).mouseup(function(){
				this.src = this.src.replace("_a.","_i.");
			});
	},
	init: function(locality){
		if(locality == null) {
			locality = "body";
		}
		this.targetBlank(locality);
		this.inputAutoClear(locality);
		this.imgRollover(locality);
	}
}

//Featured Scroller on the Homepage
var slideshowObj = {
	running: true,
	animating: false,
	numFeatures: 0,
	navID: "",
	goToSlide: function(teamID){
		
		slideshowObj.running = false;
		slideshowObj.currentSlide = $('#featured_scroller li.active').attr('id').substr(9);
		if(slideshowObj.navID != slideshowObj.currentSlide){
			$('#featured_scroller li.active').removeClass('active');
			$('#scroller_'+slideshowObj.navID).addClass('active');
			$('#scroller_nav li.active').removeClass('active');
			$('#scroller_nav_'+slideshowObj.navID).addClass('active');
			$('#scroller_'+slideshowObj.navID).fadeIn("slow",function(){
				$('#scroller_'+slideshowObj.currentSlide).hide();
			});
			if($('.teamScroller').length){
				$('#team_list li a').removeClass('active');
				$('#team_list li a#teammember_'+slideshowObj.navID).addClass('active');
			}
		}else{
			return false;
		}
	},
	nextSlide: function() {
		if(slideshowObj.running == true){
			slideshowObj.slideNumber = $('#featured_scroller li.active').attr('id').substr(9);
			slideshowObj.slideNumber = parseInt(slideshowObj.slideNumber);
			if(slideshowObj.slideNumber < slideshowObj.numFeatures){//Not the last project
				$('#featured_scroller li.active').removeClass('active');			
				$('#scroller_nav li.active').removeClass('active');			
				slideshowObj.slideNumber++;			
				$('#scroller_'+slideshowObj.slideNumber).addClass('active');			
				$('#scroller_nav_'+slideshowObj.slideNumber).addClass('active');			
				$('#scroller_'+slideshowObj.slideNumber).fadeIn("slow",function(){
					$('#scroller_'+(slideshowObj.slideNumber - 1)).hide();
				});
				if($('.teamScroller').length){
					$('#team_list li a').removeClass('active');
					$('#team_list li a#teammember_'+slideshowObj.navID).addClass('active');
				}
			}else{
				slideshowObj.firstSlideFade();
			}
			return false;
		}else{
			return false;
		}
	},
	startTime: function() {
		setInterval("slideshowObj.nextSlide()",5000);
	},
	firstSlideFade: function() {
		$('#featured_scroller li.active').removeClass('active');
		$('#scroller_nav li.active').removeClass('active');								
		$('#scroller_1').addClass('active');
		$('#scroller_nav_1').addClass('active');
		$('#scroller_1').fadeIn("slow",function(){
			$('#scroller_'+slideshowObj.numFeatures).hide();
		});
		if($('.teamScroller').length){
			$('#team_list li a').removeClass('active');
			$('#team_list li a#teammember_1').addClass('active');	
		}
	},
	init: function() {
		if($('#scroller')){
			if ($('#home #scroller').length) {
				slideshowObj.animating = true;
			}else{
				slideshowObj.running = false;
			}
			slideshowObj.numFeatures = $('#featured_scroller').children().length;
			slideshowObj.startTime();
			$('li.scrollerNav a').click(function(e){
				slideshowObj.navID = $(this).parent().attr('id').substr(13);
				slideshowObj.goToSlide();
				return false;
			});
			if($('.teamScroller').length){
				$('.teamFrame').click(function(e){
					slideshowObj.navID = $(this).attr('id').substr(11);
					slideshowObj.goToSlide();
					//Scroll To
					$.scrollTo('#featured_scroller', 300);
					return false;
				});
			}
		}
	}
}
var FancyBox = {
	boxen: function(){
		if($('.fancybox').length){
			$('a.fancybox').fancybox({
				'hideOnContentClick' : false,
				'zoomSpeedIn' : 300,
				'zoomSpeedOut' : 300
			});
		}
		if($('.gmap').length){
			$('.gmap').fancybox({
				'hideOnContentClick' : false,
				'zoomSpeedIn' : 300,
				'zoomSpeedOut' : 300,
				'frameWidth' : 840,
				'frameHeight' : 450,
				'callbackOnShow': function(){
					GMapLoader();
					if($('#fancy_right').length)$('#fancy_right').hide();
					if($('#fancy_left').length)$('#fancy_left').hide();
					getDirections.init();
					DOMUtilities.inputAutoClear("body");
				}
			});
		}
	},	
	init: function(){
		this.boxen();	
	}
}
var DatePicker = {
	init: function(){
		if($('#input_appt-date').length){
			datePickerController.datePickers["input_appt-date"];	
		}
	}
}

var CouponEmail = {
	animating: false,
	submitForm: function(){
		$('.sendToFriend input.send').click(function(e){
			var sendFormID = $(this).attr('id').split('_',3);
			$.post(
				'/coupons/coupon_email.php',
				$('#coupon_'+sendFormID[2]+'_form').serialize(),
				function(response){
					if(response.success){
						if (!$('.successMessage').length) {
							var newdiv = document.createElement('div');
							$(newdiv).addClass('successMessage');
							$(newdiv).text('This coupon has been sent to your friend!');
							$(newdiv).css('display','none');
							$('#coupon_' + sendFormID[2]).append(newdiv);
							$(newdiv).fadeIn("slow",function(){
								$(newdiv).animate({opacity: 1.0}, 2000);
								$(newdiv).fadeOut("slow",function(){
									var emailButton = $(".emailIt[href='#coupon_"+sendFormID[2]+"']");
									CouponEmail.hideForm('coupon_'+sendFormID[2],emailButton);
									$(newdiv).remove();
								});
							});
						}
					}
				},
				'json'
			);
			e.preventDefault();
			return false;
		});
		
	},
	showForm: function(formID,button){
		CouponEmail.animating = true;
		$('#'+formID).slideDown('normal',function(){
			CouponEmail.animating = false;
			button.addClass('active');
			});
	},
	hideForm: function(formID,button){
		CouponEmail.animating = true;
		$('#'+formID).slideUp('normal',function(){
			CouponEmail.animating = false;
			button.removeClass('active');
			});
	},
	init: function(){
		if($('.sendToFriend').length){
			$('.sendToFriend').hide();
			CouponEmail.submitForm();
		}
		if($('a.emailIt').length){
			$('a.emailIt').click(function(e){
				if (CouponEmail.animating == false) {
					hrefVal = $(this).attr('href').substr(1);
					if (!$(this).hasClass('active')) {
						CouponEmail.showForm(hrefVal, $(this));
					}
					else {
						CouponEmail.hideForm(hrefVal, $(this));
					}
				}
				return false;
			});
		}
	}
}
var CouponPrint = {
	couponPopup: function(couponURL){
		window.open(couponURL,"Convoy Auto Coupon Offer","menubar=no,location=no,toolbar=no,statusbar=no,resizable=no,width=500,height=300");
	},
	init: function(){
		if($('.printIt').length){
			$('.printIt').click(function(){
				couponURL = $(this).attr('href');
				CouponPrint.couponPopup(couponURL);
				return false;
			});
		}
	}
}
 var FriendsTab = {
 	tab: function(hrefVal,tabLink){
		$('#tab_container a').removeClass('active');
		tabLink.addClass('active');
		$('.friendsList').hide();
		$('#'+hrefVal+'_list').show();
		CufonFonts.init();
	},
	init: function(){
		if($('#tab_container').length){
			$('#tab_container a').click(function(){
				hrefVal = $(this).attr('href').substr(1);
				if(!$(this).hasClass('active')){
					FriendsTab.tab(hrefVal,$(this));
				}
				return false;
			});
		}
	}
 }
 var startForms = {
 	addValidator: function(formID){
		window.validateForms[formID] = new FormValidator(formID);
	},
 	init: function(){
		if($('#form_appointment').length){
			formID = 'form_appointment';
			startForms.addValidator(formID);
		}
		if($('.couponForm').length){
			var x = $('.couponForm').length;
			for (var i=0; i<x; i++) {
				var formID	= $('.couponForm:eq('+i+')').attr('id');
				formID = String(formID);
				startForms.addValidator(formID);
			};
			$('.couponForm').submit(function(e){
				e.preventDefault();
				if($('#input_firstname').val() == 'First Name' || $('#input_lastname').val() == 'Last Name'){
					if($('#input_firstname').val() == 'First Name'){
						$('#input_firstname').parents('li#li_fname').addClass('error');
					}
					if($('#input_lastname').val() == 'Last Name'){
						$('#input_lastname').parents('li#li_lname').addClass('error');
					}
				}else{
					if (window.validateForms['form_coupons-discounts'].validate()) {
						cpml_save(document.getElementById('form_coupons-discounts'));
					}	
				}
				return false;
			});
			$('#input_firstname').keyup(function(){
				if(this.value != this.defaultValue){
					$('#input_firstname').parents('li#li_fname').removeClass('error');
				}
			}).blur(function(){
				if(this.value == this.defaultValue){
					$('#input_firstname').parents('li#li_fname').addClass('error');
				}
			});
			$('#input_lastname').keyup(function(){
				if(this.value != this.defaultValue){
					$('#input_lastname').parents('li#li_lname').removeClass('error');
				}
			}).blur(function(){
				if(this.value == this.defaultValue){
					$('#input_lastname').parents('li#li_lname').addClass('error');
				}
			});
			$('#input_email').keyup(function(){
				if(this.value != this.defaultValue){
					$('#input_email').parents('li#li_email').removeClass('error');
				}
			}).blur(function(){
				if(this.value == this.defaultValue){
					$('#input_email').parents('li#li_email').addClass('error');
				}
			});
		}
	}
 }
var Appointment = {
	make: function(){
		$.post(
			'/codebehind/appointment.php',
			$('#form_appointment').serialize(),
			function(response){
				if(response.thanksPage){
					var thanksPage = response.thanksPage;
					window.location = thanksPage;	
				}
				
			},
			'json'
		);
		return false;
	},
	init: function(){
		if($('#form_appointment').length){
			window.validateForms['form_appointment'] = new FormValidator('form_appointment');
			$('#input_btn_submit').click(function(e){
				if (window.validateForms['form_appointment'].validate()) {
					e.preventDefault();
					Appointment.make();	
				}
			});
		}
	}
}
var map = null;
var geocoder = null;
var directionsPanel;
var directions;
function GMapLoader(addressSubmit){
  if (GBrowserIsCompatible()) {
    var map = new GMap2(document.getElementById("map_canvas"));
	var geocoder = new GClientGeocoder();
	var convoyIcon = new GIcon(G_DEFAULT_ICON);
	convoyIcon.image = "http://convoyautorepair.com/images/map_icon.png";
	convoyIcon.shadow = "http://convoyautorepair.com/images/map_icon_shadow.png";
	convoyIcon.iconSize = new GSize(42,27);
	convoyIcon.shadowSize = new GSize(42,27);
	convoyIcon.iconAnchor = new GPoint(12,30);
	convoyIcon.infoWindowAnchor = new GPoint(10, 30);
	markerOptions = {icon:convoyIcon};
	
	var address = 'Convoy Auto Repair and Towing, 3909 Convoy St, San Diego, CA';
	if(addressSubmit){
		directionsPanel = document.getElementById("directions_output");
		$(directionsPanel).html('');
		directions = new GDirections(map, directionsPanel);
		directions.load("from: "+addressSubmit+" to: "+address);
		$(directionsPanel).css({
			'width' : '220px',
			'height' : '343px',
			'background-image' : 'none',
			'margin-bottom' : '10px' 
		});
		if($('#directions_print').length){
			$('#directions_print').remove();
		}
		$(directionsPanel).after('<div id="directions_print"><a href="http://maps.google.com/maps?f=d&source=s_d&saddr='+address+'&daddr='+addressSubmit+'&hl=en" target="_blank">View on Google to Print Directions</a></div>');			
	}
	
	geocoder.getLatLng(address,function(point){
		if(!point){
			
		}else{
			map.setCenter(point, 14);
			var marker = new GMarker(point, markerOptions);
			 GEvent.addListener(marker, "mouseover", function() {
			    marker.openInfoWindowHtml('<span class="">Convoy Auto Repair<br />3909 Convoy St., San Diego, CA 92111<br />Phone: 858.560.9131</span>');
			  });
			map.addOverlay(marker);
				map.setUIToDefault();
			
			var customUI = map.getDefaultUI();
			map.setMapType(G_NORMAL_MAP);
		}
	});
  }
}

var getDirections = {
	get: function(addressSubmit){
		GMapLoader(String(addressSubmit));
	},
	init: function(){
		if($('#get_directions').length){
			$('#get_directions').submit(function(e){
				e.preventDefault();
				var addressSubmit = $('#input_address').attr('value');
				if(addressSubmit == 'Your Address'){
					alert('Please enter your address to get directions');
					return false;
				}else{
					getDirections.get(addressSubmit);
				}
			});
		}
	}
}
