$(document).ready(function() {
	
	/*
	$(function(){
		$('.timepicker').timepickr();
	});
	*/
		
	new AjaxUpload('photoswap', {
		action: '/events/entry/?callmethod=photoUpload',
		onChange: function (file, ext) {
			$("#logomessage").html("Upload In Progress");
		},
		onComplete: function(file, response) {
			$("#logomessage").html("Upload Complete<br>Image ID: "+response);
			$("#eventLogo").attr("src", "/showImage/"+response+"/sq175/").show();
			$("#logoImage").val(response);
			$("#logomessage").html("<p>If this image is insufficient please click the image to update it.</p>");
		}
	});
	
	/* basic show/hide for form */
	$('.showhide-toggle').live('click',function() {
		$(this).parent().children('.showhide-toggle').toggleClass("active");
		$(this).siblings('.showhide').slideToggle();
		if ( $(this).children("#enter_own_location") ) {
			$("#enter_own_location").hide();
			$(".venue-results ul").html("");
			$('.venue-results label').html("Your current location is:");
		}
	});
	
	$('.use-venue').click(function() {
		$(this).parent().children('.use-venue').removeClass("active");
		$(this).addClass("active");
	});


	$('.weekday-recursion').live('click',function() {
		
		if ($(this).find("input[type=checkbox]").is(":checked")){
			$(this).removeClass("active");
			$(this).find("input[type=checkbox]").attr("checked",false);
		}else{
			$(this).addClass("active");
			$(this).find("input[type=checkbox]").attr("checked",true);
		}

	});
	
	$('.swap-link').live('click', function() {
		$(this).hide();
		$(this).next('.swap').fadeIn();
		$(this).next('.swap').children('.save-link').fadeIn();
	});
	//$('.date-line:first .add-label').hide();
	$('.date-line .add-label').live('click',function() {
		$(this).addClass('swapped');
		$(this).removeClass('add-label');
	});
	$('input.time-label').live('click',function() {
		$(this).attr("value","");
	});
	
		
	
	
	
	/*
	----------------------------------------------------------
	Validation
	----------------------------------------------------------
	*/
	
	function addDateRules(){
		jQuery.each($('.single-events li input.startdate'), function(){
			$('#'+$(this).attr('id')).rules('remove');
			$('#'+$(this).attr('id')).rules('add', {
				required: true,
				date: true
				//,validStart: true
				,messages: {
					required: "Please enter a date."
					//,validStart: "Please enter a valid start date."
				}
			});
		});
	}
	
	function addTimeRules(){
		jQuery.each($('.single-events li input.timepicker'), function(){
			$('#'+$(this).attr('id')).rules('remove');
			$('#'+$(this).attr('id')).rules('add', {
				time: true,
				validTimeRange: true
			});
		});
	}

	jQuery.validator.addMethod("time", function(value, element) {
			return this.optional(element) || /^([0-9]|[0-1][0-9]):([0-5][0-9])\s{0,1}(AM|PM|am|pm|aM|Am|pM|Pm{2,2})$|^([0-9]|[1][0-9])\s{0,1}(AM|PM|am|pm|aM|Am|pM|Pm{2,2})$/.test(value);
		}, "Enter a valid time, 00:00 am/pm"
	);

	jQuery.validator.addMethod('validStart',function(value,element){
			parent_li = $(element).parent().parent().attr('id');
			start_date = $('#'+parent_li+' input.startdate').datepick("getDate");

			if($(element).hasClass('.startdate')){
				if(jQuery.datepick.formatDate('yymmdd',start_date) < jQuery.datepick.formatDate('yymmdd',cur_date)){
					return false;
				} else {
					return true;
				}
			}
		},
		'Need a later start date'
	);
	
	$.validator.addMethod('validTimeRange',function(value,element){
            return true;
			parent_li = '#'+$(element).parent().parent().attr('id');
									
			start_time = $(parent_li+' .timepicker:eq(0)').val();
			end_time = $(parent_li+' .timepicker:eq(1)').val();
			
            return true;
			if(start_time && end_time){
			
				stime = start_time.replace(/:/,'').split(' ');
				etime = end_time.replace(/:/,'').split(' ');
				
				if(stime[1] == etime[1]){
					if(stime[0] < etime[0] || (stime[0] >= 1200 && etime[0] <= 1100)){
						return true;
					} else {
						return false;
					}
				} else {
					return true;
				}
			
			} else if(!start_time && end_time){
				return false;
			} else if(start_time && !end_time){
				return true;
			} else if(!start_time && !end_time) {
				return true;
			} else {
				return false;
			}
			
		},
		'Please enter a valid time range'
	);


	$.validator.addMethod('validVenue',function(value,element){
		
			if( !$("#vzip").val()){
				if (!$('#enter_own_location').hasClass('active')) {
					$('#enter_own_location').click();
				}
				return false;
			} else {
				return true;
			}
			
		},
		'Please choose a venue below &darr;'
	);

	jQuery.validator.addMethod("phone", function(phone_number, element) {
		phone_number = phone_number.replace(/\s+/g, ""); 
		return this.optional(element) || phone_number.length > 9 &&
			phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
	}, "Please specify a valid phone number");


	$('#addContactYes').click(function(){
		$('#contactName').rules('add',{ required: true });
		$('#address').rules('add',{ required: true });
		$('#city').rules('add',{ required: true });
		$('#state').rules('add',{ required: true });
		$('#zip').rules('add',{ required: true });
		$('#phone').rules('add',{ required: true });
	});

	$('#addContactNo').click(function(){
		$('#contactName').rules('remove');
		$('#address').rules('remove');
		$('#city').rules('remove');
		$('#state').rules('remove');
		$('#zip').rules('remove');
		$('#phone').rules('remove');
	});

	$('#repeating').click(function(){
		$('.single-events li:gt(1)').remove();
		$('#addDateLine').hide();
		$('#non_repeating').removeClass("active");
		$('#recurring-options').slideDown('fast');
	});

	$('#non_repeating').click(function(){
		$('#addDateLine').show();
		$("#repeating").removeClass("active");
		$('#recurring-options').slideUp('fast');
	});
	
	$('#eventEntryForm').validate({
		rules: {
			'event[title]': { required: true, maxlength:100 },
			'eventList[0][location][title]': { required: true, maxlength:100, validVenue:true },
			'types[0]': { required: true },
			'event[body]': { required: true },
			'eventList[0][date][0][sdate]': { required: true }
			//'event[contactEmail]': { required: true, email: true}
		},
		showErrors: function(errorMap, errorList) {
			if (this.numberOfInvalids() == 0) {
				$("#errorlist").hide();
			} else {
				var message = "<h3>There are " + this.numberOfInvalids() + " errors:</h3><p>";

				for (var i in errorList) {
					message += errorList[i].message + "<br/>";						
				}

				$("#errorlist").html("<div class='mod basic basic-ext color2'><div class='inner'><div class='hd'></div><div class='bd'>"+message+"</p></div><div class='ft'></div></div></div>");
				$("#errorlist").show();
										
				this.defaultShowErrors();

				$.scrollTo("#errorlist");
			}
		},
		messages: {
			'event[title]': 'Please enter a title.',
			'eventList[0][location][title]': {
				required: 'Please add a location.',
				validVenue: 'Please enter a zip code.'
			},
			'types[0]': 'Please select at least one category.',
			'event[body]': 'Please enter a description.',
			'eventList[0][date][0][sdate]': 'Please enter a date.',
			'event[contactEmail]': 'Please enter a valid email address.'
		},
		onkeyup: false,
		onfocusout: false,
		onclick: false,
		focusInvalid: false					
	});
	
	/*
	----------------------------------------------------------
		Datepicker
	----------------------------------------------------------
	*/

    cur_date = new Date();

	var date_options = { beforeShow: customRange, showOn: 'both', buttonImageOnly: true, buttonImage: 'http://s3.amazonaws.com/wimgo/images/icon_calendar.png',
		onSelect: function(dates) { 
			var stimeinput = "#" + $(":parent:parent .single-entry-starts input").attr('id');
			var etimeinput = "#" + $(":parent:parent .single-entry-ends input").attr('id');
			
			if (!$(stimeinput).val()) {
				d = new Date();
				var cur_hour = d.getHours();
				var cur_min = d.getMinutes();
				var cur_ampm = "am";

				if (cur_min >= 1) cur_hour++;
				
				if (cur_hour == 24 || cur_hour == 0) cur_hour = 12;
				
				if (cur_hour > 12) {
					cur_hour -= 12;
					cur_ampm = "pm";
				}

				$(stimeinput).val(cur_hour + ":00 " + cur_ampm);
				$(etimeinput).val((cur_hour+1) + ":00 " + cur_ampm);
				//alert("here");
			}
		}
	 };
	var time_options = { convention: 12, handle: true };
	
	$('.datepick').datepick(date_options);
	
	$('.startdate,.enddate').live('click', function(){
		id = $(this).attr("id");
		$('#'+id).datepick(date_options);
	});
	
	function customRange(input){
		if($('#repeating').hasClass('active')){
			return {minDate: ( $(input).hasClass('enddate') ? 
				$('.single-events li:eq(0) input.startdate').datepick("getDate") : cur_date), maxDate: ( $(input).hasClass('startdate') ? $('#end-repeat').datepick("getDate") : (cur_date.getMonth()+1)+'/'+cur_date.getDate()+'/'+(cur_date.getFullYear()+1) ) };
		} else {					
			return { minDate: cur_date, maxDate: (cur_date.getMonth()+1)+'/'+cur_date.getDate()+'/'+(cur_date.getFullYear()+1) };
		}
	}

	/*
	----------------------------------------------------------
		Saving, editing dates
	----------------------------------------------------------
	*/

	single_event_count = 0;
	
	$('#addDateLine').click(function(){
		
		single_event_date_count++;
		
		li = '<li id="date'+single_event_date_count+'" class="date-line added">'+
			'<span class="single-entry-date">'+
				'<input id="sdate'+single_event_date_count+'" class="startdate datepicker form-text" type="text" name="eventList[0][date]['+single_event_date_count+'][sdate]" autocomplete="off"/>'+
			'</span>'+
			'<span class="single-entry-starts">'+
				'<input id="stime'+single_event_date_count+'" type="text" name="eventList[0][date]['+single_event_date_count+'][stime]" class="timepicker form-text"/>'+
			'</span>'+
			'<span class="to">to</span>'+
			//* '<input id="edate'+single_event_date_count+'" class="enddate datepicker text" type="text" name="eventList[0][date]['+single_event_date_count+'][edate]">'+
			'<span class="single-entry-ends">'+
				'<input id="etime'+single_event_date_count+'" type="text" name="eventList[0][date]['+single_event_date_count+'][etime]" class="timepicker endtime form-text"/>'+ 
			'</span>'+
			'<span class="allday"><input type="checkbox" class="form-checkbox" id="allday'+single_event_date_count+'"> <label for="allday'+single_event_date_count+'">All Day</label></span>'+
			'<a class="button button-small add-label swap-link"><span>Add Label</span></a>'+
			'<input id="label0" class="swap form-text bg-color14 time-label" name="eventList[0][date]['+single_event_date_count+'][label]"/>'+
			'<a class="button button-secondary button-small remove-date" href="javascript:void(0)"><span><i class="unicon">x</i></span></a>'+
		'</li>';

		$('.single-events').append(li);
		$('.date-line:first .add-label').fadeIn();
		$('.date-line:first .form-help').fadeIn();
		$('.date-line:first .add-label.swapped').removeClass("add-label");
		$('.startdate,.enddate').datepick(date_options);
		
		addDateRules();
		addTimeRules();

	});
	
	$('.remove-date').live('click', function() {
		if(single_event_date_count > 0) {
			$(this).parent().remove();
			single_event_date_count--;
			//reOrderListIds();
		}
	});

	/* Location */
	$("#event-location").keyup(function(){
		if($(this).val() != '') throttle(getVenues,500);
	});

	$('.use-venue').live('click',function(){
		var venue_button = $(this);

		setTimeout(function() {
			$(venue_button).text('Use this');
		}, 2000);
	});

	$(".recurrence").change(function(){
		$("." + this.value).show().siblings().hide();
		$("." + this.value + " > select").removeAttr("disabled");
		
		// enable weekly dayfreq
		if($(this).val() == 2){
			$.each($('.repeat-weekly .repeat-items input'), function(){
				$(this).removeAttr('disabled');
			});
		}
		
		$('#monthly-bydaydays,#monthly-bydayfreq').attr('disabled','disabled');
		
	});

	$("select.interval").change(function(){
		var value = $(this).val();
		$('#recurrence-interval').val(value);
	});

	$('.allday').live('click',function(){

			parent_li = $(this).parent().attr('id');
			
			$('#'+parent_li+' .timepicker').val('');
			
			if($('#'+parent_li+' span input[type=checkbox]').is(':checked')){
				$('#'+parent_li+' .timepicker,#'+parent_li+' .to,#'+parent_li+' .time-note:not(:first)').addClass('disabled');
			} else {
				addTimeRules();
				$('#'+parent_li+' .timepicker,#'+parent_li+' .to,#'+parent_li+' .time-note:not(:first)').removeClass('disabled');
			}
			
	});

	$('.by-day-freq,.by-day-days').live('click', function(){
		$('.monthselection1').attr('checked','');
		$('.monthselection2').attr('checked','checked');
	});
	
	$('.by-month-day').live('click', function(){
		$('.monthselection2').attr('checked','');
		$('.monthselection1').attr('checked','checked');
	});
	
	$('.monthselection1').click(function(){
		$('#monthly-bymonthday').removeAttr('disabled');
		$('#monthly-bydaydays,#monthly-bydayfreq').attr('disabled','disabled');
	});
	
	$('.monthselection2').click(function(){
		$('#monthly-bydaydays,#monthly-bydayfreq').removeAttr('disabled');
		$('#monthly-bymonthday').attr('disabled','disabled');
		
		// disable weekly dayfreq
		$.each($('#repeat-weekly .repeat-items input'), function(){
			$(this).attr('disabled','disabled');
		});
		
	});

	$('#newEvent').live('click',function(){
		window.location = "/events/entry";									
	});
					
	// inital rules
	addDateRules();
	addTimeRules();

	$('.location-change').toggle(function(){
		$('.location-center span:eq(0)').hide();
		$('.location-center span:eq(1),.location-center select,.location-center small').show();
		$(this).children("span").text('SAVE');
		$(this).addClass("button-primary");
	},function(){
		showLoader(1);
		getLatLon($('#eventLocationSearch').val());
	});

	$('#reset-location').click(function(){

		$("#venuealert").slideUp();

		// hide location inputs
		$("#enter_own_location").trigger("click");
		
		// hide the button
		//$("#enter_own_location").hide();

		// clear the search results
		$(".venue-results ul").html('');
		
		// values
		$('#event-location').val('');
		$("#venueId").val('');
		$("#event-location").val('');
		$("#vaddress1").val('');
		$("#vaddress2").val('');
		$("#vcity").val('');
		$("#vstate").val('');
		$("#vzip").val('');
		$("#vphone").val('');
		
	});
	
}); // dom ready








function throttle(method,timeout,scope) {
	scope = scope || window;
	timeout = timeout || 250;

	clearTimeout(method.__throttle);
		method.__throttle = setTimeout(function(){
		method.call(scope);
	}, timeout);
}

var venues;

function useVenue(num){

	$('#venuealert .venue-results label').html("Your current location is:");

	// pop field values
	$("#venueId").val(venues[num].venueId);
	$("#event-location").val(venues[num].title);
	$("#vaddress1").val(venues[num].address1);
	$("#vaddress2").val(venues[num].address2);
	$("#vcity").val(venues[num].city);
	$("#vstate").val(venues[num].state);
	$("#vzip").val(venues[num].zip);
	$("#vphone").val(venues[num].phone);

	// hide the button
	$("#enter_own_location").hide();
	$("#venuealert .showhide:hidden").slideDown("fast");

	// clear the search results
	$(".venue-results ul").html('');
	
	// validate location title (validVenue)
	$("input[name='eventList[0][location][title]']").valid();
}

function showLoader(bool){
	if(bool){
		$('.loader').fadeIn();
	} else {
		$('.loader').fadeOut();
	}

}	

function getLatLon(loc) {
	loc = loc.replace(",", "+");
	loc = loc.replace(" ", "+");
	$.ajax({
		type: "POST",
		url: "/api?method=Location.GetGeo&location="+loc,
		dataType: "json",
		success: function(json){
			if(json.success){
			
				$('.location-center span:eq(0)').text('Within '+ $('#geoRad').val() +' miles of ' + json.location);

				$('.location-center span:eq(1),.location-center select,.location-center small').hide();
				$('.location-center span:eq(0)').show();
				$('.location-change').children("span").text('CHANGE');
				$('.location-change').removeClass("button-primary");
				$('.location-error').text('');
				$("#geoLat").val(json.geo.latitude);
				$("#geoLon").val(json.geo.longitude);
				
				showLoader(0);
			
			} else {
			
				$('.location-error').text("Can't set this location! Try again.");
				showLoader(0);

			}
		}
	});

}

/**
	-------------------------------------------------
	adding spotlight for admin
	__________________________________________________
**/
	
	

function addToSpotlight(id) {
	
	if (id) {
		$.ajax({
					type: "POST",
					url: "/events/entry/ajax/",
					data: "func=addSpotlight&eventId="+$("#eventId").val()+"&checked="+$('#spotlight').attr('checked'),
					dataType: "json",
	
					success: function(json){					

							$('#spotLightStatus').html("<p>"+json+"</p>");
							
							$('#spotLightStatus').fadeIn();
						}
	
					});
				}
}	




function getVenues(){
	
	showLoader(1);
	
	$.ajax({
			type: "POST",
			url: "/events/entry/ajax/",
			data: "method=location&_filterSearch="+escape( $("#event-location").val() )+"&lat="+$("#geoLat").val()+"&lon="+$("#geoLon").val()+"&rad="+$("#geoRad").val(),
			dataType: "json",
			success: function(json){

                if( json.success == true ) {
                    json = json.content;
                } else {
                    return;
                }
				
				if(json.Error){
				
					//$('.alert-icon').removeClass('map').addClass('question');
					$('#venuealert .venue-results label').html("We couldn't find any close matches near "+ $('#eventLocationSearch').val() +". Try another search.").show();
					
					$("#venuealert .active").removeClass("active");
					
					$('#venuealert ul').html('');
					
					$("#venuealert").slideDown();
					
					showLoader(0);
				
				} else {
				
					$('#venuealert .venue-results label').html("We found some close matches:");
					
					$("#venuealert .active").removeClass("active");
										
					venues = json;
					
					$('#venuealert ul').html('');
					
					$.each(json,function(i){
						if (json[i].title.length != '') { venue_title = '<a href="/business/'+ json[i].venueId+'" target="_blank">'+ json[i].title +'</a><br/>' } else { venue_title = ''; }
						if (json[i].address1.length != '') { venue_address1 = json[i].address1 +', '; } else { venue_address1 = ''; }
						if (json[i].address2.length != '') { venue_address2 = json[i].address2 +', '; } else { venue_address2 = ''; }
						if (json[i].city.length != '') { venue_city = json[i].city +', '; } else { venue_city = ''; }
						if (json[i].state.length != '') { venue_state = json[i].state; } else { venue_state = ''; }
						if (json[i].zip.length != '') { venue_zip = ' '+ json[i].zip; } else { venue_zip = ''; }
						if (json[i].phone.length != '') { venue_phone = '<br/><b class="color10 txt-sub">Phone: '+ json[i].phone +'</b>'; } else { venue_phone = ''; }
						$('#venuealert ul').append('<li class="basic-row"><div class="f-right"><a onclick="useVenue('+i+');" class="button button-small use-venue onoff"><span>Use this</span></a></div>'+ venue_title + venue_address1 + venue_address2 + venue_city + venue_state + venue_zip + venue_phone + '</li>');
					});
					
					$("#venuealert").slideDown();
					$("#enter_own_location").show();
					showLoader(0);
					
				}
			}
	})
}

//$(function(){ $('.events-entry-photo').equalHeights(); });

