/*!
 * Created By: Gasoline Creative Group (http://gasolinecreative.com)
 * CountDownClock/Counter
 * Version 1.2;
 */

(function($){
	$.fn.digits = function(){ 
		    return this.each(function(){ 
		        $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")); 
		    })
		}
		
		
		function digits(NUM){
			return NUM.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"); 
		}
		
		function adjustTime(time){
			if(time<0){
				switch(time){
					case -1:
					return 23;
					break;
					case -2:
					return 22;
					break;
					case -3:
					return 21;
					break;
				}
			}else{
				return time;
			}
		}
			var todaysDate = new Date();
		var ajustTzone;
		var daysOfTheMonth = [31,29,31,30,31,30,31,31,30,31,30,31];
		
	$.fn.addCountDownClock = function(options){
		// default configuration properties
		var defaults = {
			DisplayDate:false,
			DisplayTime:"12:00 AM",
			EndDate: "", 						// FORMAT: [MM/DD/YYYY]
			EndTime: "",
			TimeZone: "Same", 					// OPTIONS: ["Same","PST","MST","CST","EST"]
			TimeUnits: "Automatic",
			RevealType: "hiddenDiv", 			// OPTIONS: ["hiddenDiv", "redirect"]
			Hidden: false, 						// OPTIONS: [true, false]
			RevealDiv: "",						// This is the Div that shows after count down ends
			RevealUrl: "",
			Delimiters:false,
			DuringCountDown:null,
			Blink:false
		}
		var options = $.extend(defaults, options);  
			var widgetTemp = this;
			switch (options.TimeZone){
				case "Same":
				TimeZone = (todaysDate.getTimezoneOffset()/60);
				break;
				case "PST":
				TimeZone = 8;
				break;
				case "MST":
				TimeZone = 7;
				break;
				case "CST":
				TimeZone = 6;
				break;
				case "EST":
				TimeZone = 5;
				break;
			}			

			ajustTzone =(todaysDate.getTimezoneOffset()/60) - TimeZone;
			
			
		if(options.DisplayDate){
			var DisplayYear =  Number(options.DisplayDate.split("/")[2]);
			var DisplayMonth =  Number(options.DisplayDate.split("/")[0]);
			var DisplayDay =  Number(options.DisplayDate.split("/")[1]);			
			var DisplayTime = options.DisplayTime.split(" ")[0];
			var DisplayTimeOfDay = options.DisplayTime.split(" ")[1].toLowerCase();
		
			if(DisplayTimeOfDay == "pm"){
				if(Number(DisplayTime.split(':')[0])==12){
					var dpHour = Number(DisplayTime.split(':')[0]);
				}else{
					var dpHour = Number(DisplayTime.split(':')[0])+12;
				}
				var dpMin = Number(DisplayTime.split(':')[1]);
			}else if(DisplayTimeOfDay == "am"){
				if(Number(DisplayTime.split(':')[0])==12){
					var dpHour = 0;
				}else{
					var dpHour = Number(DisplayTime.split(':')[0]);
				}
				var dpMin = Number(DisplayTime.split(':')[1]);
			}
			

			DisplayMonth--;
			if((dpHour-ajustTzone)<0){
				if(DisplayDay==1){
					DisplayMonth--;
					DisplayDay = daysOfTheMonth[DisplayMonth];
				}else{
					DisplayDay--;
				}
			}
			
			dpHour = adjustTime(dpHour-ajustTzone);
			
			var DisplayDate = new Date(DisplayYear, DisplayMonth, DisplayDay,dpHour,dpMin,0);
			var DisplayUpdateInterval;

		
			checkStart();
		}else{
			buildClock();
		}
		
		function checkStart(){
			if(!(DisplayDate <= new Date())){
				var timeRemaining = ((DisplayDate - new Date())/1000)/60;
				if(timeRemaining < 1){
					clearInterval(DisplayUpdateInterval);
					DisplayUpdateInterval = setInterval(function (){checkStart()},1000);
				}else if(timeRemaining > 1){
					clearInterval(DisplayUpdateInterval);
					DisplayUpdateInterval = setInterval(function (){checkStart()},60000);
				}
			}else{
				clearInterval(DisplayUpdateInterval);
				buildClock();
			}
		}
		
		
		function buildClock(){
			widgetTemp.each(function() {
				var EndYear =  Number(options.EndDate.split("/")[2]);
				var EndMonth =  Number(options.EndDate.split("/")[0]);
				var EndDay =  Number(options.EndDate.split("/")[1]);			
				var EndTime = options.EndTime.split(" ")[0];
				var EndTimeOfDay = options.EndTime.split(" ")[1].toLowerCase();
				var TimeUnitsInt;
				
				var obj = $(this);
				var html='<div class="clearfix" style="text-align:center;"><div id="unit1" class="digits"><div class="timeUnit"></div><div class="timeDigit"></div></div><div class="colon"></div><div id="unit2" class="digits"><div class="timeUnit"></div><div class="timeDigit"></div></div><div class="colon"></div><div id="unit3" class="digits"><div class="timeUnit"></div><div class="timeDigit"></div></div><div class="colon"></div><div id="unit4" class="digits"><div class="timeUnit"></div><div class="timeDigit"></div></div></div>';
				
				obj.html(html);
				if(options.DuringCountDown){
					$(options.DuringCountDown).show();
				}
				
				
				obj.addClass("countDownWidget");
				if(options.Hidden == "true"){
					obj.css('display','none');
				}
				if(options.RevealType == "hiddenDiv"){
					$("#"+options.RevealDiv).hide();
				}
				
				if(options.Delimiters){
					$(".colon").html("<div>"+options.Delimiters+"</div>");
					if(options.Blink){
						$(".colon>div").addClass("blink");
						$('.blink').blink(10000);
					}
				}
				
				var timeUnitArray = [{label:"weeks", value:0},{label:"days", value:0},{label:"hours", value:3600000},{label:"minutes", value:60000},{label:"seconds", value:1000}];
				var timeUpdate = [60000,60000,1000];
				
				if(EndTimeOfDay == "pm"){
					if(Number(EndTime.split(':')[0])==12){
						var sHour = Number(EndTime.split(':')[0]);
					}else{
						var sHour = Number(EndTime.split(':')[0])+12;
					}
					var sMin = Number(EndTime.split(':')[1]);
				}
				else if(EndTimeOfDay == "am"){
					if(Number(EndTime.split(':')[0])==12){
						var sHour = 0;
					}else{
						var sHour = Number(EndTime.split(':')[0]);
					}
					var sMin = Number(EndTime.split(':')[1]);
				}
				
				
				EndMonth--;
				if(sHour-ajustTzone<0){
					if(EndDay==1){
						EndMonth--;
						EndDay = daysOfTheMonth[EndMonth];
					}else{
						EndDay--;
					}
				}
				
				sHour = adjustTime(sHour-ajustTzone);
				var clockEnding = new Date(EndYear, EndMonth, EndDay,sHour,sMin,0);
				
				var updateInterval;
				
				function calculateTime() {
					var todaysDate = new Date();
					gmtHours = -todaysDate.getTimezoneOffset()/60;
					var timeZoneIndex=-4-gmtHours;
					
					if(todaysDate>clockEnding){
						clearInterval(updateInterval);
						if(options.RevealType == "hiddenDiv"){
							obj.remove();
							$("#"+options.RevealDiv).show();
						}
						if(options.RevealType == "redirectUrl"){
							obj.remove();
							window.location.replace(options.RevealUrl);
						}
					}else{
						if(!(clockEnding <= todaysDate)){
							if(options.TimeUnits=="Automatic"){
								var tRemaining = ((clockEnding - todaysDate)/1000)/60;
								if(tRemaining > (1440*7)){
									TimeUnitsInt=0;
								}else if(tRemaining > 1440){
									TimeUnitsInt=1;
								}else if(tRemaining < 1440){
									TimeUnitsInt=2;
								}
							}else{
								if(options.TimeUnits=="Weeks,Days,Hours"){
										TimeUnitsInt=0;
									}else if(options.TimeUnits=="Days,Hours,Minutes"){
										TimeUnitsInt=1;
									}else if(options.TimeUnits=="Hours,Minutes,Seconds"){
										TimeUnitsInt=2;
									}else if(options.TimeUnits=="Days,Hours,Minutes,Seconds"){
										TimeUnitsInt=1;
									}								
								}
							clearInterval(updateInterval);
							updateInterval = setInterval(function () {calculateTime()}, timeUpdate[options.TimeUnits == "Days,Hours,Minutes,Seconds"?2:TimeUnitsInt]);
						}
						obj.find("#unit1 .timeUnit").html(timeUnitArray[TimeUnitsInt]['label'].toUpperCase());
						obj.find("#unit2 .timeUnit").html(timeUnitArray[TimeUnitsInt+1]['label'].toUpperCase());
						obj.find("#unit3 .timeUnit").html(timeUnitArray[TimeUnitsInt+2]['label'].toUpperCase());
						if(options.TimeUnits=="Days,Hours,Minutes,Seconds"){
						obj.find("#unit4 .timeUnit").html(timeUnitArray[TimeUnitsInt+3]['label'].toUpperCase());
						}

					}
					
					difSeg = Math.floor((clockEnding-todaysDate)/1000);
					Hours = Math.floor((difSeg/60)/60);
					Secs = Math.floor(difSeg%60);
					
					difMin = Math.floor(difSeg/60);
					Mins = difMin%60;
					
					if(TimeUnitsInt==0){
						Days = Math.floor(Hours/24);
						Weeks = Math.floor(Days/7);
						Days = Math.floor(Days%7);
						Hours = Math.floor(Hours%24);
						timeUnitArray[0]['value'] = formatNumber(Weeks);
						timeUnitArray[1]['value'] = formatNumber(Days);
						timeUnitArray[2]['value'] = formatNumber(Hours);
					}else if(TimeUnitsInt==1){
						Days = Math.floor(Hours/24);
						Hours = Math.floor(Hours%24);
						timeUnitArray[1]['value'] = formatNumber(Days);
						timeUnitArray[2]['value'] = formatNumber(Hours);
						timeUnitArray[3]['value'] = formatNumber(Mins+1);
						timeUnitArray[4]['value'] = formatNumber(Secs);
						
					}else if(TimeUnitsInt==2){
						Hours = Math.floor(Hours);
						timeUnitArray[2]['value'] = formatNumber(Hours);
						timeUnitArray[3]['value'] = formatNumber(Mins);
						timeUnitArray[4]['value'] = formatNumber(Secs);
					}
		
					obj.find("#unit1 .timeDigit").html(timeUnitArray[TimeUnitsInt]['value']);
					obj.find("#unit2 .timeDigit").html(timeUnitArray[TimeUnitsInt+1]['value']);
					obj.find("#unit3 .timeDigit").html(timeUnitArray[TimeUnitsInt+2]['value']);
					if(options.TimeUnits=="Days,Hours,Minutes,Seconds"){
					obj.find("#unit4 .timeDigit").html(timeUnitArray[TimeUnitsInt+3]['value']);
					}
				}
				
				function formatNumber(input){
					if(input<10){
						return "0"+input;
					}else{
						return input;
					}
				}
				
				calculateTime();	
			});
		}
	}
	
	
	$.fn.addCounter = function(options){
		// default configuration properties
		var defaults = {
			DisplayDate:false,
			TimeZone: "Same",
			DisplayTime:'',
			StartDate: "", 	// FORMAT: [MM/DD/YYYY]
			DollarAmount: ".02"
		}
		var options = $.extend(defaults, options);
		
			var todaysDate = new Date();
			gmtHours = -todaysDate.getTimezoneOffset()/60;
			timeZoneIndex=-4-gmtHours;
			
			var widgetTemp = this;
			switch (options.TimeZone){
				case "Same":
				TimeZone = (todaysDate.getTimezoneOffset()/60);
				break;
				case "PST":
				TimeZone = 8;
				break;
				case "MST":
				TimeZone = 7;
				break;
				case "CST":
				TimeZone = 6;
				break;
				case "EST":
				TimeZone = 5;
				break;
			}
			
			var todaysDate = new Date();
/*
			gmtHours = -todaysDate.getTimezoneOffset()/60;
			timeZoneIndex=-4-gmtHours-1;
*/		
			ajustTzone =(todaysDate.getTimezoneOffset()/60) - TimeZone;

		if(options.DisplayDate){
			var DisplayYear =  Number(options.DisplayDate.split("/")[2]);
			var DisplayMonth =  Number(options.DisplayDate.split("/")[0]);
			var DisplayDay =  Number(options.DisplayDate.split("/")[1]);			
			var DisplayTime = options.DisplayTime.split(" ")[0];
			var DisplayTimeOfDay = options.DisplayTime.split(" ")[1].toLowerCase();
		
			if(DisplayTimeOfDay == "pm"){
				if(Number(DisplayTime.split(':')[0])==12){
					var dpHour = Number(DisplayTime.split(':')[0]);
				}else{
					var dpHour = Number(DisplayTime.split(':')[0])+12;
				}
				var dpMin = Number(DisplayTime.split(':')[1]);
			}
			else if(DisplayTimeOfDay == "am"){
				if(Number(DisplayTime.split(':')[0])==12){
					var dpHour = 0;
				}else{
					var dpHour = Number(DisplayTime.split(':')[0]);
				}
				var dpMin = Number(DisplayTime.split(':')[1]);
			}

			DisplayMonth--;
			if(dpHour-TimeZone<0){
				if(DisplayDay==1){
					DisplayMonth--;
					DisplayDay = daysOfTheMonth[DisplayMonth];
					}else{
					DisplayDay--;
				}
			}
			
			dpHour = adjustTime(dpHour-TimeZone);
			
			var DisplayDate = new Date(DisplayYear, DisplayMonth, DisplayDay,dpHour,dpMin,0);
			var DisplayUpdateInterval;
			checkStart();
		}else{
			buildCounter();
		}
		
		function checkStart(){
			if(!(DisplayDate <= new Date())){
				var timeRemaining = ((DisplayDate - new Date())/1000)/60;
				if(timeRemaining < 1){
					clearInterval(DisplayUpdateInterval);
					DisplayUpdateInterval = setInterval(function (){checkStart()},1000);
				}else if(timeRemaining > 1){
					clearInterval(DisplayUpdateInterval);
					DisplayUpdateInterval = setInterval(function (){checkStart()},60000);
				}
			}else{
				clearInterval(DisplayUpdateInterval);
				buildCounter();
			}
		}
		
		
		function buildCounter(){
			widgetTemp.each(function() {
				var StartYear =  Number(options.StartDate.split("/")[2]);
				var StartMonth =  Number(options.StartDate.split("/")[0]);
				var StartDay =  Number(options.StartDate.split("/")[1]);
				var updateInterval;
					clearInterval(updateInterval);
					updateInterval = setInterval(function () {increaseNumber()}, 10);
				
				var obj = $(this);
				var clockEnding = new Date(StartYear, StartMonth-1, StartDay);
				
				function increaseNumber(){
				var todaysDate = new Date();
					obj.html('<div class="clearfix dollarAmount">$'+digits((((todaysDate-clockEnding)/1000)*options.DollarAmount).toFixed(2))+'</div>');
					obj.addClass("counterWidget");
				}	
			});
		}

	}


})(jQuery);
