/*
 * Object used to control select boxes
 */
var select = function($selects){
	this.initSelects($selects);
}

//inits all select boxes
//wraps span around select, adds selected value, binds event
select.prototype.initSelects = function($selects){
	
	var self = this;
	
	for(a = 0; a < $selects.length; a++){
		
		//get individual select el
		var $el = $($selects[a]);
		
		if(!$el.parent('span.savvy-select').length){
		
		var adminStyle = '';
		if($el.hasClass('admin')){
			adminStyle = 'admin';
		}
		
		$el.wrap('<span class="savvy-select ' + adminStyle +  '"></span>');
		var $parent = $el.parent('.savvy-select:eq(0)');
		
		//get selected text
		var $selectedEl = $el.children(':selected');
		if($selectedEl.length){
			selectValue =  $selectedEl.text();
		}
		
		$parent.append('<span class="selectVal ' + adminStyle +  '">'+selectValue+'</span>');
		
		var selectWidth = $parent.width();
		var selectHeight = $parent.height();
		var selectPadding = $parent.css('paddingRight').split('px');
		
		selectPadding = parseFloat(selectPadding[0]);
		$el.width(selectWidth+selectPadding);
		$el.height(selectHeight);
		
		$el.bind('change', function(){
			self.onChange(this);
		});
		
		}
	}	
}
//function used for change event on select el
select.prototype.onChange = function(el){
	
	$changedEl = $(el);
	var selectValue = $changedEl.children(':selected').text();
	
	var $selectValSpan = $changedEl.next('.selectVal');
	$selectValSpan.text(selectValue);
	var $parent = $changedEl.parent('.savvy-select');
	
	var selectPadding = $parent.css('paddingRight').split('px');
	selectPadding = parseFloat(selectPadding);
	var newWidth = $selectValSpan.width() + selectPadding;
	$changedEl.css({'width': newWidth});
}


// ================================================================================================ 
// ! Class ::  Form
//
//this class will control the sign-in that is in the header of all pages   
// ================================================================================================ 


var signIn = function(){
	

	var self = this;
	
	$('.signInSubmit').bind('click',function(){
		$btn = $(this);
		$btn.after("<span id='orderProcessing'><img src='/images/loading.gif' alt='loading'/></span>");
		self.submitForm('signIn',$btn.parents('form:eq(0)'));
	});
	
	$('.forgotPasswordBtn').bind('click',function(){
		$btn = $(this);
		$btn.after("<span id='orderProcessing'><img src='/images/loading.gif' alt='loading'/></span>");
		self.submitForm('forgotPassword',$btn.parents('form:eq(0)'))
	});
	
	$('.createAccountBtn').bind('click',function(){
		$btn = $(this);
		$btn.after("<span id='orderProcessing'><img src='/images/loading.gif' alt='loading'/></span>");
		self.submitForm('createAccount',$btn.parents('form:eq(0)'))
	});
		
}

signIn.prototype.submitForm = function(formType,form){
	
	var self = this;
	
	var credentials = form.serialize();
	
	credentials += '&formType=' + formType + '&ajax=1';
	
	$.ajax({
		data: credentials
		,type: 'POST'
		,url: '/inc/ajaxSignIn.php'
		,dataType: 'json'
		,success:function(data){
		
			$('#orderProcessing').remove();
			
			if(Number(data['success']) == 1){
				self.successDelegation(data, formType);	
			}else{
				errorBox('Error', data['msg']);
			}
		}
		,error:function(data){
			errorBox('Error', 'Internal error, please try again.');
		}
	});
}

signIn.prototype.successDelegation = function(data, formType){
	
	if(window.location.pathname.indexOf('logout') > -1){
		var newLocation = window.location.href.replace('logout/', '');
		newLocation = newLocation.replace('logout', '');
	}else{
		
		var newLocation = window.location.protocol+"//"+window.location.host;
	
		if(data['returnUrl']){
			newLocation = newLocation + "/" + data['returnUrl'];	
		}else{
			newLocation = newLocation + window.location.pathname;
		}
	
	}

	if(formType == 'signIn'){
		
		var symbol = '?';
		if(newLocation.indexOf('?') > -1){
			symbol = '&';
		}
		
		window.location = newLocation + symbol + 'alert=true&msg=' + escape(data['msg']);
	}else if(formType == 'forgotPassword'){
		alertBox('Success!', data['msg']);
	}else if(formType == 'createAccount'){
		
		var locationId = $('#location').val();
		var mcSubscribe = new subscribeTop();
		
		var callback = function(){
			alertBox('Success!', data['msg'], function(){ window.location = newLocation; }, 500);
		}	
		
		mcSubscribe.sendAjax(data['email'], locationId, true, callback);
		
	}
	
}

// ================================================================== 
// ! Class used to control share controls at the top of offer papge   
// ================================================================== 


var share = function(){

		
}

share.prototype.init = function(){
	
	var self = this;
	
	$('#emailForm').bind('submit',function(){
		self.getEmailData();
	});
}

share.prototype.getEmailData = function(){
	
	var self = this;
	
	var data = {};
	
	$(".btnSend").css("opacity","0.5");
	$(".btnSend").attr("disabled","disabled");
	
	//data.frmEl = cleanStr($("#emailForm").val());
	data.sName = cleanStr($("#senderName").val());
	data.rName = cleanStr($("#recieverName").val());
	data.sEmail = cleanStr($("#senderEmail").val());
	data.rEmail = cleanStr($("#recieverEmail").val());
	data.message = cleanStr($("#message").val());
	data.location = cleanStr($("#location").val());
	data.dealId = cleanStr($('#dealId').val());
	data.token = cleanStr($("#token").val());
	data.contact = true;
	data.xml = true;
	data.method = 'shareEmail';
	
	self.sendAjax(data);
}

share.prototype.sendAjax = function(data){
	
	var self = this;
	
	$.ajax({
		url: '/inc/ajaxEmails.php'
		,data: data 
		,type: 'POST'
		,dataType: 'json'
		,success: function(data){
			
			if(Number(data.success) == 1){
				self.resetForm(data);
			}else{
				errorBox('Error', data['msg']);
			}
			
		}
		,error:function(){ errorBox('Error', 'Internal error, please try again.'); }
	});

}

share.prototype.resetForm = function(data){
	
	var self = this;
	
	$(".btnSend").css("opacity","1");
	$(".btnSend").removeAttr("disabled");
	
	var fieldArea = $("#emailForm");
	
	$('#emailLayer').hide();
	alertBox('Success!', data['msg']);
	
	$(':input', fieldArea).each(function() {
		var type = this.type;
		var tag = this.tagName.toLowerCase();
	
		if(type == 'text' || tag == 'textarea'){
			this.value = "";	
		}
	});
	
	var frmEl = $("#senderName");
	frmEl.focus();
}

//cleans string for ajax post
share.prototype.cleanStr = function(str){
	
	var cStr = str;
	
	cStr = cStr.replace(/&/g,"**am**");
	cStr = cStr.replace(/=/g,"**eq**");
	cStr = cStr.replace(/\+/g,"**pl**");
	
	return cStr;
}

// ========================================================================================================================================================================================================================================================================================================================================= 
// ! This class is used for the subscribe functionality located in the header of the public facing pages.
// it will get the location and emailaddress of the user subscribing and post the data through an ajax request.
// after the data is posted and email sent, the class will alert the user about the success of the email/errors.   
// ========================================================================================================================================================================================================================================================================================================================================= 

subscribeTop = function(){

}

subscribeTop.prototype.initTop = function(){
	
	var self = this;
	
	//get location id
	var locationId = $('#location').val();
		
	//add event to button
	$('.subscribeTop').bind('click',function(){
		
		//honeypot - should be empty
		var $hp = $(this).siblings('input[type=hidden]:eq(0)');
		
		if($hp.val() == ''){
			
			//get email address and validate
			var email = $(this).siblings('input[type=text]:eq(0)').val();
			var emailRegEx = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
			
			if (!emailRegEx.test(email)) {
				
				//email is not valid - throw error
				errorBox('Error', 'Please enter a valid email address.');
				$('#subscribeEmail').focus();
			
			}else{
				
				//all good, send ajax
				self.sendAjax(email, locationId);
			}
			
		}else{
			//this should never happen, if your seeing this you are a bot
			if(widnow.console){console.log('Honeypot test failed.');}
		}
		
	});

}

subscribeTop.prototype.sendAjax = function(email, locationId, signUp, callback){
	
	var self = this;
	
	if(signUp == null){
		signUp = false;
	}
	
	//create data array that gets sent in ajax request
	data = {};
	data.email = email;
	data.locationId = locationId;
	data.method = 'subscribeTop';
	
	if(!signUp){
		self.disableBtns();
	}
	
	//ajax
	$.ajax({
		url: '/inc/ajaxEmails.php'
		,data: data 
		,type: 'POST'
		,dataType: 'json'
		,success: function(data){
			
			if(Number(data.success) == 1){
							
				if(signUp){
					callback();
				}else{
					alertBox('Success!', data['msg']);
					self.enableBtns();
				}
				
				if(isLive){
					self.googleTracking(data);
					self.localTracking(data);
				}
				
			}else{
				errorBox('Error', data['msg']);
			}
			
		}
		,error:function(){ errorBox('Error', 'An internal error occured, please try again.'); }
	});
}

subscribeTop.prototype.disableBtns = function(){
	$("#subscribeBtnTop").css("opacity","0.5");
	$("#subscribeBtnTop").attr("disabled","disabled");
	$("#subscribeBtnTop").addClass("loading");
	
	return this;
}

subscribeTop.prototype.enableBtns = function(){
	$("#subscribeBtnTop").css("opacity","1");
	$("#subscribeBtnTop").attr("enabled","enabled");
	$("#subscribeBtnTop").removeClass("loading");
	$('#subscribeEmail').val('');
	
	return this;
}

subscribeTop.prototype.googleTracking = function(data){
	
	//google analytics
	var pageTracker = _gat._getTracker("UA-11094057-1");
	pageTracker._trackPageview("/subscribe-" + data['location']);
	
	//adWords signup conversion
	switch(data['location']){
		case 'Cleveland':
			var trackingHTML = '<div style="display:inline;"><img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/1027479852/?value=0&amp;label=yMl_CLL6lAEQrLL46QM&amp;guid=ON&amp;script=0"/></div>';
			$('body').append(trackingHTML);
			break;
		case "Nashville":
			var trackingHTML = '<div style="display:inline;"><img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/1027479852/?value=0&amp;label=VUHHCIz7lAEQrLL46QM&amp;guid=ON&amp;script=0"/></div>';
			$('body').append(trackingHTML);
			break;
		default:
			if(window.console){console.log('No location returned from ajax call - unable to track adwords campaign')}
			break;
	}

}

subscribeTop.prototype.localTracking = function(data){

	var location = '';
	var email = '';
	
	if(data.location){
		location = escape(data.location);
	}
	
	if(data.email){
		email = escape(data.email);
	}
	
	var trackingHTML = '<iframe src="https://www.lontrk.com/confirm?aid=1053&type=registration&ref='+email+'&market='+location+'" scrolling="no" frameborder="0" width="1" height="1" style="display:none;"></iframe>';
	$('body').append(trackingHTML);
}

$(document).ready(function() {
	/****************************
	GLOBAL MISCELANEOUS UI
	****************************/
		
	//Text Fields
	$(".textField .text").focus(function() {
		if($(this).val()==''){
			$(this).prev('label').animate({opacity: ".3"}, 100);
		}
	});
	$(".textField .text").keydown(function() {
		$(this).prev('label').animate({opacity: "0"}, 80, function(){
			$(this).hide()
		});
	});
	$(".textField .text").blur(function(){
		if($(this).val()==''){
			$(this).prev('label').show();
			$(this).prev('label').animate({opacity: "1"}, 100);
		}
	});
	
	$('.text[placeholder]').each(function(){
		if(!($.browser.safari && $.browser.version.substr(0,1) >= 4)){
			var placeholder = $(this).attr('placeholder');
			if($(this).attr('value')==''){
				$(this).attr('value', placeholder);
				$(this).focus(function(){
					if($(this).attr('value')==placeholder){
						$(this).attr('value', '');
					}
				});
				$(this).blur(function(){
					if($(this).attr('value')==''){
						$(this).attr('value', placeholder);
					}
				});
			}
		}
	
	});
	//Buttons
	$('.btn').hover(function() {
		$(this).addClass('hover');
	}, function() {
		$(this).removeClass('hover');
	});
	$('.btn').mousedown(function() {
		$(this).addClass('active');
	});
	$('.btn').mouseup(function() {
		$(this).removeClass('active');
	});
	$('.btn').focus(function(){
		$(this).addClass('hover');
	});
	$('.btn').blur(function(){
		$(this).removeClass('hover');
	});
	
	//Close Buttons
	$('.btnClose').live('click',function(){
		$(this).closest('.formBox').hide();
		if($(this).closest('.formBox').attr('id')=='alertBox'){
			$(this).closest('.formBox').remove();
		}
	});
	
	
	//Even out Columns
	$(window).load(function(){
		evenColumns();
	});
	
	
	
	//Preload FormBox Image
	var image1 = $('<img />').attr('src', '../images/BGFormBox.png');
	
	/*******************************
	SPECIFIC UI PIECES
	*******************************/
	//City Select Layer
		$('#btnCitySelect').click(function(){
			$('#cityLayer').show();
		});
		$('#btnCityClose').click(function(){
			$('#cityLayer').hide();
		});
	
	//Share Buttons
		
		$(".shareEmail").click(function(){
			$("#emailLayer").show();
		});
		
	//Sign in Sign Out UI
		$("#signInOutNav").live('click', function(){
			$("#signInOutLayer").show();
			$(this).addClass('activated');
		});
		$("#signInOutLayer .btnClose").live('click', function(){
			$('#signInOutNav').removeClass('activated');
		});
		$("#signInOutNav.activated").live('click', function(){
			$("#signInOutLayer").hide();
			$("#forgotPassLayer").hide();
			$("#createAccountLayer").hide();
			$('#signInOutNav').removeClass('activated');
		});
		$('.createAccountLink').live('click', function(){
			$("#signInOutLayer").hide();
			$("#forgotPassLayer").hide();
			$("#createAccountLayer").show();
		});
		$("#createAccountLayer .btnClose").live('click', function(){
			$('#signInOutNav').removeClass('activated');
		});
		$('.forgotPassLink').live('click', function(){
			$("#signInOutLayer").hide();
			$("#createAccountLayer").hide();
			$("#forgotPassLayer").show();
		});
		$("#forgotPassLayer .btnClose").live('click', function(){
			$('#signInOutNav').removeClass('activated');
		});
		
		$("#signOutNav").live('click',function(){
			$("#signOutLayer").show();
			$(this).addClass("activated");
		});
		$("#signOutLayer .btnClose").live('click', function(){
			$('#signOutNav').removeClass('activated');
		});
		
		$("#navLogout").live('click', function(){
			$.ajax({
				url: '/myaccount/logout'
				,data: '' 
				,type: 'POST'
				,success: function(data){
					var protocol = window.location.protocol;
					var host = window.location.host;
					window.location=protocol+'//'+host + '?alert=true&msg=You are now logged out';
					 
				}
				,error:function(){ errorBox('Error', 'An internal error occured, please try again.'); }
			});
			return false;
		});
		
		/*************************************
		HOMEPAGE FACEBOOK AND TWITTER WIDGET 
		*************************************/
		$(".widgetNav").click(function(){
			$(".widgetNav").removeClass('selected');
			$(this).addClass('selected');
			if($(this).attr('id')=="twitterWidgetNav"){
				$("#facebookWidgetWrap").hide();
				$("#twitterWidgetWrap").show();
			} else if($(this).attr('id')=="facebookWidgetNav"){
				$("#twitterWidgetWrap").hide();
				$("#facebookWidgetWrap").show();
			}
			return false;
		});
	/************************
	RADIO BUTTONS
	************************/
	$(".radio").addClass('savvy-radio-default');
	$(".radio").each(function(){
		var thisID = $(this).attr("id");
		$(this).add($('label[for='+thisID+']')).wrapAll("<span class='savvy-radio'></span");
		$(this).wrap("<span class='savvy-radio-button'></span>");
		if($(this).attr("checked")==true){
			$(this).closest('.savvy-radio').addClass('active');
		}
	});
	$('.savvy-radio').mousedown(function() {
		$(this).addClass('down');
	});
	$('.savvy-radio').mouseup(radioUp);
	function radioUp(){
		$(this).removeClass('down');
		$(this).find(":radio").trigger('click');
		$(this).find(":radio").change();
		var radioSet = $(this).find(":radio").attr("name");
		$(":radio[name="+radioSet+"]").closest(".savvy-radio").removeClass("active");
		$(this).addClass('active');
	}
	/************************
	CHECKBOXES
	************************/
	$(".checkbox").addClass('savvy-checkbox-default');
	$(".checkbox").each(function(){
		$(this).add($(this).next()).wrapAll("<span class='savvy-checkbox'></span>");
		var thisLabel = $(this).next();
		$(this).wrap("<span class='savvy-checkbox-button'></span>");
		if($(this).attr("checked")==true){
			$(this).closest('.savvy-checkbox').addClass('active');
		}
	});
	$('.savvy-checkbox').mousedown(function() {
		$(this).addClass('down');
	});
	$('.savvy-checkbox').mouseup(function(){
		$(this).find(":checkbox").trigger('change');
	});
	$('.checkbox').change(changeThisCheckbox);
	function changeThisCheckbox(){
		$(this).closest('.savvy-checkbox').removeClass('down');
		if($(this).attr("checked")==true){
			$(this).closest('.savvy-checkbox').removeClass('active');
			$(this).attr("checked", false);
		} else {
			$(this).closest('.savvy-checkbox').addClass('active');
			$(this).attr("checked", true);
		}
	}
	
	/*
	*	Init classes
	*/
	
	var $selects = $('.select');
	if($selects.length){
		var selectObj = new select($selects);
	}
	
	var $signIn = $('form#signInForm');
	if($signIn.length){
		var signInObj = new signIn();
	}
	
	//alerts being passing in through the query string
	if($.query){
		
		if($.query.get('alert') && $.query.get('alert') == 'true'){
		
			alertBox('Success', $.query.get('msg'));
		
		}else if($.query.get('alert')){
		
			var string = $.query.get('alert');
			string = string.decodeBase64();
			
			for(var a = 0; a < string.length; a++){
				var char = string.charAt(a);
				if (char == '}'){
					var charIndex = a + 1;
				}
			}
			
			string = string.slice(0, charIndex);
			
			var obj = JSON.parse(string);
			if(obj){
				if(obj.on){
					if(obj.heading == 'Error'){
						alertBox('Error', obj.msg);
					}else{
						alertBox('Success', obj.msg);
					}
				}
			}
		}
		
	}
	
	//dynamic alerts being stored in hidden input
	$dynamicAB = $('input.dynamicAlertBox:eq(0)');
	if($dynamicAB.length){
		var alertType = $dynamicAB.attr('rel');
		var alertMsg = $dynamicAB.val();
		
		if(alertType.toLowerCase() == 'error'){
			alertBox('Error', unescape(alertMsg));
		}else if(alertType.toLowerCase() == 'success'){
			alertBox('Success', unescape(alertMsg));
		}
	}
				
	
	
	if($('div#shareDeal').length){
		var shareObj = new share();
		shareObj.init();
	}
		
	if($('.subscribeTop').length){
		var subscribeTopObj = new subscribeTop();
		subscribeTopObj.initTop();
	}
	
	
	$('form.dontSubmit').unbind('submit');
	
	/*
	$('.select').each(function(){
		$(this).wrapAll('<span class="savvy-select"></span>');
		var selectValue = $(this+':selected').text();
		console.log(selectValue);
		$(this).parent('.savvy-select').append('<span class="selectVal">'+selectValue+'</span>');
		var selectWidth = $(this).parent('.savvy-select').width();
		var selectHeight = $(this).parent('.savvy-select').height();
		$(this).width(selectWidth);
		$(this).height(selectHeight);
	});
	$('.select').change(function(){
		var selectValue = $(this+':selected').text();
		console.log(selectValue);
		$(this).next('.selectVal').text(selectValue);
	});
	*/

	
//end of jquery dom ready	
});
	
	//console.log function that does not break IE - log_debug(arg1, arg2);
	log_debug = function() {
		if(window.console && window.console.firebug) console.log.apply(this, arguments);
	}

	//error box
	function errorBox(heading, message){
		var scrollPosition = $(window).scrollTop()+100;
		$('body').append('<div class="formBox" id="alertBox" style="position:absolute;left:50%;width:300px;margin-left:-150px;top:'+scrollPosition+'px;z-index:500"><span class="tl"></span><span class="tr"></span><div class="innerWrap"><div class="innerContent"><h4 style="color:#D23534">'+heading+'</h4><a href="javascript:;" class="btnClose red">X</a><p class="red">'+message+'</p></div></div><span class="bl"></span><span class="br"></span></div>');
	}
	
	//Alert Boxes
	function alertBox(heading, message, callback, pauseTime){
	
		if(!pauseTime){
			pauseTime = 3000;
		}
		
		var scrollPosition = $(window).scrollTop()+100;
		$('body').append('<div class="formBox" id="alertBox" style="position:absolute;left:50%;width:300px;margin-left:-150px;top:'+scrollPosition+'px;z-index:500"><span class="tl"></span><span class="tr"></span><div class="innerWrap"><div class="innerContent"><h4>'+heading+'</h4><a href="javascript:;" class="btnClose">X</a><p>'+message+'</p></div></div><span class="bl"></span><span class="br"></span></div>');
		$('#alertBox').pause(pauseTime).animate({opacity: 0}, 1000, function() {
		  $('#alertBox').remove();
		  if(callback){
		  	callback();
		  }
		});
	}
	
	function alertBoxTemp(heading, message){
		$('#newsletterBox').append('<div class="clear" style="padding-top:20px"></div><h3>'+heading+'</h3><p>'+message+'</p>');
	}
	
	//Even columns out
	function evenColumns(){
				
		var $homeMain = $('#homeMain');
		
		if($homeMain.length){
		
			var $centerColumn = $('#centerColumn');
			var $homeRight 	  = $('#homeRight');
			var $homeSidebar  = $('#homeSidebar');
			
			if($homeSidebar.height() > $centerColumn.height()){
				
				SBHeight = $homeSidebar.height();
				
				$centerColumn.height(SBHeight);
				$homeRight.height(SBHeight);
				
			}else{
				var newHeight = $homeMain.height() - 302;
				
				$centerColumn.height(newHeight);
				$homeRight.height(newHeight);
			}
						
			
		}else{
			if(($("#sidebar").length) && $("#main").height() > $("#sidebar").height()){
				$("#sidebar").height($("#main").height()+30);
				$("#content").height($("#main").height()+50);
			} else if(($("#sidebar").length) && $("#main").height() < $("#sidebar").height()){
				var sbH = $('#sidebar').height();
				var mH = $('#main').height();
				var cH = $('#content').height();
					
				//console.log(sbH + ' ' + mH + ' ' + cH);
				//$("#main").height($("#sidebar").height());
				$("#content").height(sbH + 17);
			}
		}	
		
	}
	
/*Pause Plugin for jQuery*/
$.fn.pause = function(duration) {
    $(this).animate({ dummy: 1 }, duration);
    return this;
};