var uploaded_photos = 0;

$(function() {
	// Input submit buttons are of <button> type so they can translate, this allows us
	// to give them a button-submit class and for them to behave as expected.
	$('.button-submit').click(function() {
		$(this).closest('form').submit();
	});

	$('.invite_fb_friends').click(function() { 
		FB.ui({
			method: 'apprequests',
			message: 'Come create an account on Help Me Rent!',
		});
	});

	$('.facebook_login').click(function() {
		FB.login(function(response) {
			if (response.authResponse || response.session) {
				FB.api('/me', function (response) {
					var query_string_array = [];

					query_string_array.push('first_name='+response.first_name);
					query_string_array.push('last_name='+response.last_name);

					if (typeof response.location != 'undefined' && typeof response.location.name != 'undefined') {
						var location_data = response.location.name.split(', ');
						query_string_array.push('city='+location_data[0]);
						query_string_array.push('state='+location_data[1]);
					}

					if (typeof response.work != 'undefined' && typeof response.work[0] != 'undefined' && typeof response.work[0].employer != 'undefined' && typeof response.work[0].employer.name != 'undefined') {
						query_string_array.push('company='+response.work[0].employer.name);
					}

					if (typeof response.email != 'undefined') {
						query_string_array.push('email='+response.email);
					}

					if (typeof response.username != 'undefined') {
						query_string_array.push('facebook_link=http://www.facebook.com/profile.php?id=' + response.id);
						query_string_array.push('profile_picture=https://graph.facebook.com/' + response.id + '/picture');
					}

					if (typeof response.work != 'undefined' && typeof response.work[0] != 'undefined' && typeof response.work[0].position != 'undefined' && typeof response.work[0].position.name != 'undefined') {
						query_string_array.push('occupation=' + response.work[0].position.name);
					}

					window.location.href = 'register?social=1&' + query_string_array.join('&');
				});
			}
		}, {scope: 'email'});
	});

	$('#logout-link').click(function () {
		var href = this.href;
		FB.getLoginStatus(function (response) {
			if (response.authResponse || response.session) {
				FB.logout(function (response) {
					window.location.href = href;
				});
			} else {
				window.location.href = href;
			}
		});

		return false;
	});
	
	$('.login_with_facebook').click(function(){
		FB.login(function(response) {
			if (response.authResponse || response.session) {
				window.location.href = '/facebook/login';
			}
		}, {scope: 'email'});
	})
	
	$('.popup .popup_submit').live('submit',function(){ 
		popup_submit($(this));
		return false;
	})
	$('.popup .popup_close, .popup .overlay').live('click',function(){	
		popup_close();
	})
	
	$('.popup_button, .popup_link').click(function(){
		popup($(this).attr('href'));
		return false;
	})
	
	$('.schedule_showing').click(function(){ 
		form = $('#form-schedule_showing');
		href = form.attr('action');
		href += '?'+form.serialize();
		if(formRequired(form)) {
			popup(href);
		}
		return false;
	})
	
	$('.make_offer').click(function(){ 
		form = $('#form-make_offer');
		href = form.attr('action');
		href += '?'+form.serialize();
		if(formRequired(form)) {
			popup(href);
		}
		return false;
	})
	
	$('a.advanced_search').click(function() {
		$('div.advanced_search').fadeIn('fast');
	});

	$(document).keydown(function(e) {
		if (e.which == 27) {
			popup_close();
		}
	});

	
	$('#change_profile_picture').change(function () {
		$(this).next('input').click();
	});

	$('.popup_link').live('click', function () {
		$('#popup_header').html($(this).data('title') + '<a href="javascript:void(0);" class="close_popup">Close</a>');

		$('#popup_content').load($(this).data('view'), function() {
			$('#popup_wrapper').fadeIn('fast');
		});
	});

	$('a[rel=lightbox]').lightBox();

	// Connect profiles to social sites.
	
	$('.profile_connect_facebook').click(function() {
		FB.login(function(response) {
			if (response.authResponse || response.session) {
				location.href='/profiles/facebook_connect';
			}
		}, {scope: 'email'});
	});

	$('select[name=id_listing_type]').change(function() {
		var label = $(this).children('optgroup').children('option:selected').text().toLowerCase();

		$('.type_dependent_fields').hide();

		switch (label) {
			case 'residential':
				$('.'+label).show();
				break;
			case 'commercial':
				$('.'+label).show();
				break;
			case 'vacation':
				$('.'+label).show();
				break;
		}
	});
	
	//amenities or description
	if(getHash()=='detail-amenities'){
		$('#amenities').show();
	} else {
		$('#description').show();
	}
	
	$('.show_description').click(function(){
		$('#amenities').hide();
		$('#description').show();
	});
	$('.show_amenities').click(function(){
		$('#description').hide();
		$('#amenities').show();
	});
	
	//tabs: photos videos map
	if(getHash().indexOf('show-')>-1){
		id = str_replace('show-','',getHash());
		$('#button-'+id).addClass('button-blue');
		if(id=='map'){ 
			initMap($('#map.data').html());
		}
		$('#holder-'+id).show();
	} else {
		$('.button-tab:first').addClass('button-blue');
		$('.tab-holder:first').show();
	}
	$('.button-tab').click(function(){
		//buttons
		$('.button-tab').removeClass('button-blue');
		$(this).addClass('button-blue');
		
		//tabs (content)
		$('.tab-holder').hide();
		id = str_replace('button-','',$(this).attr('id'));
		tab_id = '#holder-'+id;
		if(id=='map' && $('#map-placeholder').html()==''){
			initMap($('#map.data').html());
		}
		$(tab_id).show();
	});
	
	//LISTING CREATE
	$('#type[name=address]').blur(function(){ 
		var elem = $(this);
		setTimeout(function(){ 
			if(elem.is(':focus')==false){
				var address = $('#type[name=address]').val();
				/*var src = '<iframe width="360" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.com/?ie=UTF8&amp;t=m&amp;vpsrc=0&amp;q='+encodeURI(address)+'&amp;z=15&amp;output=embed"></iframe>';
				$('#map-holder').html(src);*/
				if(address!='') {
					initMap(address,'#map-holder');
				}
			}
		},100);
	})
	
	//EDIT LISTING
	if($('#form-edit_listing').size()>0){
		var address = $('#type[name=address]').val();
		if(address!='') {
			initMap(address,'#map-holder');
		}
	}
	
	$('#unit').blur(function(){
		var address = $('#type[name=address]').val();
		if($(this).val()!=''){
			address += '<br />Unit #'+$(this).val();
		}		
		$('#address-holder').html(address);
	});
	
	if($('#form-create_listing').size()>0) {
		$('.amenities:first').show();
	}
	
	//FORM VALIDATION
	$('form').live('submit',function(){ 
		IeFixVals($(this));
		var allow = true;
		
		$(this).find('input, textarea, select').each(function(intIndex){
			if($(this).attr('type')!='radio' && $(this).attr('type')!='hidden' && $(this).hasClass('required')==true) {
				if($(this).val()==''){
					alert('Required fields have to be filled in.');
					$(this).focus();
					$(this).addClass('highlighted');
					allow = false;
					return false;
				} else if($(this).attr('name')=='email' && !verifyEmail($(this).val())){
					alert('Please enter a valid email address.');
					$(this).focus();
					$(this).addClass('highlighted');
					allow = false;
					return false;
				} else {
					$(this).removeClass('highlighted');
				}
			}
		})
		
		var id = $(this).attr('id');
		if(allow) {
			if(id=="form-create_listing" && uploaded_photos==0 && $(this).find('input[type=file]').val()==''){
				alert('At least one photo is required to post your rental');
				allow = false;
			}
		}
		
		if(!allow){
			return false;
		}
	});
	
	//PURCHASE CREDITS
	$('.change_pack').click(function(){
		val = $(this).val();
		$('#option'+val).attr('selected',true);
	})
	
	$('#credits').change(function(){
		$('.change_pack').attr('checked',false);
	})
	
	
	$('select[name=id_listing_type]').change();
	$('.datepicker').datepicker();
	$('.datepicker').live('click',function(){
		$(this).datepicker('destroy').datepicker().focus();
	});
	
	
	
	//SLIDESHOW CAROUSEL
	var car_mover = $('#listing_photos_list');
	var car_current = 0;
	var car_count = $('#listing_photos_list img').size()-1;
	var car_width = 110;
	var car_left = '#left';
	var car_right = '#right';
	var car_speed = 300;
	var car_shown_at_once = 5;
	var car_move_at_once = 5;
	
	if($('#albums_list').size()>0){
		car_mover = $('#albums_list');
		car_count = $('#albums_list img').size()-1;
		car_width = 144;
		car_left = '#a_left';
		car_right = '#a_right';
		car_shown_at_once = 4;
		car_move_at_once = 1;
		
		if($('#albums_list .active').size()>0){
			var index = $('#albums_list img').index($('#albums_list .active'))+1;
			if(index>car_shown_at_once){
				var new_left = (index-car_shown_at_once)*car_width;
				setTimeout(function(){
					car_mover.animate({
						left: '-='+new_left
					},car_speed)
				},500);
				car_current = index-car_shown_at_once;
			}
		}
	}

	$(car_right).click(function(){ 
		if(car_current<=car_count-car_shown_at_once) {
			car_current = car_current+car_move_at_once;
			car_mover.animate({
				left:'-='+car_width*car_move_at_once
			},car_speed);
		}
		return false;
	})
	
	$(car_left).click(function(){
		if(car_current>0) {
			car_current = car_current-car_move_at_once;
			car_mover.animate({
				left:'+='+car_width*car_move_at_once
			},car_speed);
		}
		return false;
	});
	
	$('.question').click(function(){ 
		$(this).parent().next().toggle(500);
		return false;
	});
	
	//IE placeholder fix
	if(!Modernizr.input.placeholder){
		$("input").each(
		 function(){
			 if($(this).val()=="" && $(this).attr("placeholder")!=""){
				 $(this).val($(this).attr("placeholder"));
				 $(this).focus(function(){
					if($(this).val()==$(this).attr("placeholder")) $(this).val("");
				 });
				 $(this).blur(function(){
					if($(this).val()=="") $(this).val($(this).attr("placeholder"));
				 });
			 }
		 });
	}
	
	//disable submit on enter create listing form
	$('#form-create_listing input').keypress(function(event){
		return !(window.event && window.event.keyCode == 13); 
	});

	$("#header_navigation a button").click(function () {
		// Act like they clicked on the a - using [0] because we don't just want the event.
		$(this).parent()[0].click();
	});
	
	$('#save_and_continue').live('click',function(){
		$('#confirm_account_form #email').removeClass('highlighted');
				
		if(formRequired($('#confirm_account_form'))) {
			if(verifyEmail($('#confirm_account_form #email').val())) {
				return true;
			} else {
				alert('This is not a valid e-mail address.');
				$('#confirm_account_form #email').addClass('highlighted');
				$('#confirm_account_form #email').focus();
				return false;
			}
		} else {
			return false;
		}
	});
});

function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}

function eraseCookie(name) {
createCookie(name,"",-1);
}

