var current = 0;
var photoInputCounter = 0;
var fbApiKey;

var removeOnClick = function(){
	
};
var getUserPic = function(facebook_id){
 FB.api({
		   method: 'fql.query',
		   query: 'SELECT  pic from user where uid='+facebook_id
	  },
	  function(response) 
	  {  
		  if(response[0].pic){
			document.getElementById('profile-pic').src = response[0].pic;
		  }
		  else{
			  document.getElementById('profile-pic').src = "../images/common/user-avatar.gif"
		  }
	   }  
	);	

};

var getFriendPic = function(){
	
	if($$('img').length > 0)
	  {
	  	for(var i=0; i< $$('img').length; i++)
		{
			if($$('img')[i].className =="friend_image")
			{
				var image_id = $$('img')[i].id
				FB.api(
				   		  {
				   		    method: 'fql.query',
				   		    query: 'SELECT  pic from user where uid='+ $$('img')[i].id 
				   		  },
				   		  function(response) 
				   		  { 
				   			  if(response[0].pic){
				   				
				   				document.getElementById(image_id).src = response[0].pic;
				   			  }
				   			  else{
				   				  
				   				 document.getElementById(image_id).src = "/images/common/user-avatar.gif"
				   			  }
				   		   }  
				   		);		
			}
		}
	  }	
};


var setCookie = function(c_name, value){
	document.cookie= c_name+"="+value+";path=/;";
}

var getCookie = function(c_name){
	if (document.cookie.length>0)
	  	{
	  	c_start=document.cookie.indexOf(c_name + "=");
	  	if (c_start!=-1)
		    {
	    	c_start=c_start + c_name.length+1;
	    	c_end=document.cookie.indexOf(";",c_start);
	    	if (c_end==-1) c_end=document.cookie.length;
	    	return unescape(document.cookie.substring(c_start,c_end));
	    	}
	  	}
	return "";
}

var deleteAllCookies = function() {
    var cookies = document.cookie.split(";");

    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        var eqPos = cookie.indexOf("=");
        var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
        document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
    }
}

var ajaxSubmit = function(form){
	new Ajax.Request(form.action, {
		method: 'post',
		parameters: Form.serialize(form),
		evalScript: true
	});
	return false;
};

var toggleView = function(toHide, toShow){
	$(toHide).style.display = 'none';
	$(toShow).style.display = 'block';
};

var addCarProfilePhotoInput = function(){
	$('photo_inputs_container').insert({'bottom': $('photo_input_template').innerHTML.gsub('uploaded_data', 'uploaded_data_' + photoInputCounter)});
	photoInputCounter = photoInputCounter + 1;
};

var addNewsPhotoInput = function(){
	$('photo_inputs_container').insert({'bottom': $('photo_input_template').innerHTML.gsub('uploaded_data', 'uploaded_data_' + photoInputCounter)});
	photoInputCounter = photoInputCounter + 1;
};

var checkUsernameAvailability = function(value){
	new Ajax.Request("/users/check_usermane_availability", {
		method: 'GET', parameters: {
			'username': value
		}
	})
};

var toggleForgotPasswordInput = function(emailInput){
	
	if (emailInput.id == 'dummy_email_input'){
    var dummyInput = jQuery(emailInput);
    var actuaInput = dummyInput.next('input');
    
    dummyInput.hide();
    actuaInput.show().focus();
  }else if (emailInput.value == ''){
    var actualInput = jQuery(emailInput);
    var dummyInput = actualInput.prev('input');
    
    dummyInput.show();
    actualInput.hide();
  }
	
};
var facebookFetchForRegistration = function(fbUserId){
	
	FB.api('/me', function(response) {
		if (response.name){
			$('user_full_name').value = response.name;
		}
			if (response.email){
			$('user_email').value = response.email;
		}
		if (response.birthday){
			facebookSelectBirthdateForRegistration(response.birthday);
		}
		});

	 $('img_loading').style.display = 'none';
		
};

var facebookSelectCityForRegistration = function(city){
	var options = $$('#address_city_id option');
	options.each(function(option){
		if (option.innerHTML.strip().capitalize() == city.capitalize()){
			option.selected = true;
		}
	});
};

var facebookSelectBirthdateForRegistration = function(birthdate){
	values = birthdate.gsub('/', '').split(' ').without('');
	$$('#user_birthday_3i option').each(function(option){
		if (option.innerHTML.strip() == values[1]){
			option.selected = true;
		}
	});
	$$('#user_birthday_2i option').each(function(option){
		if (option.innerHTML.strip() == values[0]){
			option.selected = true;
		}
	});
	$$('#user_birthday_1i option').each(function(option){
		if (option.innerHTML.strip() == values[2]){
			option.selected = true;
		}
	});
};

var startPhotoGallery = function(photoId){
	$$('.hidden_photo').each(function(p){p.style.display = 'none';});
	$(photoId).style.display = 'block';
	new Lightbox.base('photos_holder');
};

var startDataViewer = function(dataId){	
	new Lightbox.base(dataId);
};

var submitComment = function(){
	var commentForm = $('comment_form');
	if (commentForm['comment[title]'].value.blank() || commentForm['comment[comment]'].value.blank()){
		alert(alerts.mustEnterComment());
		return false;
	}
	ajaxSubmit(commentForm);
	$('comment_form_submit').onclick = function(){return false};
};

var commentsPage = function(type, id, page){
	new Ajax.Request("/comments", {
		method: "GET",
		parameters: {
			'commentable_type': type,
			'commentable_id': id,
			'page': page
		}
	});
};

var showPage = function(type ,id, page){
	loadin_image = $(type+'_loading');
	if (loadin_image){
		$(type+'_block').innerHTML = '';
		loadin_image.style.display = 'inline';		
	}
	new Ajax.Request("/" + type , {
		method: "GET",
		parameters: {
			'make_id': id,
			'page': page
		}
	});
};

var submitRating = function(type, id, rating, token){
	new Ajax.Request("/rating", {
		method: "POST",
		parameters: {
			'ratable_type': type,
			'ratable_id': id,
			'rating': rating,
			'authenticity_token': token,
			'return_to': window.location
		}
	});
};

var doAdminUsersFilter = function(){
	window.location = "/admin/user_types/" + $('user_type_select').value + "/statuses/" + $('status_select').value + "/users_pages/1"
};

var updateModelsSelect = function(makeId, source){
	
	toggleView('car_model_id', 'models_select_loading');
	new Ajax.Request("/users/all/cars/models_select", {
		method: "GET",
		parameters: {
			'make_id': makeId
		}
	});
};

var submitCarAdState = function(userId, car_ad_id,state, token,msg){
	
	var flag = true;
	if(state == 2)
	{
		var answer = confirm(msg);
		if(answer){
			flag = true;
		}else{
			flag = false;
		}
	}
	if(flag){
		
		var url = "/users/"+ userId + "/ads/" + car_ad_id +"/update_state";
		new Ajax.Request(url, {
			method: "POST",
			parameters: {
				'user_id': userId,
				'id': car_ad_id,
				'state': state,
				'authenticity_token': token
			}
		});
	}
	
};



var updateProfilesSelect = function(modelId, source){
	toggleView('car_car_profile_id', 'profiles_select_loading');
	new Ajax.Request("/users/all/cars/profiles_select", {
		method: "GET",
		parameters: {
			'model_id': modelId
		}
	});
};

var updateCarDetails = function(profileId){
	toggleView('car_details', 'car_details_loading');
	new Ajax.Request("/users/all/cars/car_details", {
		method: "GET",
		parameters: {
			'profile_id': profileId
		}
	});
};

var enableCarFormSubmit = function(){
	$('car_form').submit();
};

var selectCarToSell = function(carId){
	if (carId.blank()){
		$('car_form_submit').onclick = null;
		$('new_car_details').style.display = "block";
		$('color_picer_block').style.display = "block";
		$('color_input_field').name = "car[color]";
		
	}else{
		$('car_form_submit').onclick = enableCarFormSubmit;
		$('new_car_details').style.display = "none";
		$('color_picer_block').style.display = "none";
		$('color_input_field').name = "";
	}
};

var deleteAdPhoto = function(userId, adId, photoId){
	toggleView('delete_photo_' + photoId, 'delete_photo_' + photoId + '_loading');
	new Ajax.Request("/users/" + userId + "/ads/" + adId + "/delete_photo", {
		method: "GET",
		parameters: {
			'photo_id': photoId
		}
	});
};

var removeSpacesAndCommas = function(input){
	input.value = input.value.gsub(/\s|,/, '');
};

var facebookLogout = function(){
	
	FB.logout(function(response) {});

};
var insertFacebookFeed = function(full_name, data){
	 FB.ui(
			  {
			    method: 'stream.publish',
			    display: 'dialog',
			    message: full_name + ' ' + data['caption'],
			    attachment: {
			         name : data['title'],
			      description: (
			    	full_name + ' ' + data['caption']
			      ),
			      href: data['title_url'],
			      media: data['images']
			    },
			    action_links: [
			      { text: data['title'], href: data['title_url'] }
			    ]
			  }
			);
};


var getFacebookFriends2 = function(user_id,facebook_id,token){
	
	
	FB.api('/me/friends', function(response) {
		

		  var url = "/carlog_users/" + user_id + "/fill_facebook_friends";
			new Ajax.Request(url, {
				method: "POST",
				parameters: {
					'authenticity_token': token,
					'friends':  response.data.toJSON()
				}
			});
		});
	
};

var getFacebookFriends = function(carlogUsers){
	
	
	FB.api('/me/friends', function(response) {
		var firstResponse = response.data;
		
		if(firstResponse.length > 0)
		{
			  for(var i = 0; i < firstResponse.length; i++)
			  {
				  for(var j =0; j < carlogUsers.length; j++)
    			  {
					  if(firstResponse[i].id == carlogUsers[j])
		    		  {
						  FB.api(
					    		  {
					    		    method: 'fql.query',
					    		    query: 'SELECT uid, name, pic from user where uid='+firstResponse[i].id
					    		  },
					    		  function(response) 
					    		  {  	 
			    					  if (response[0].pic == null){
	    									$('friends_wrapper').insert({bottom: $('friend_template').innerHTML.gsub("blank_fid", response[0].uid).gsub("blank_src", "/images/common/small-avatar.gif").gsub("blank_name", response[0].name)});
	    							   }else{
	    									$('friends_wrapper').insert({bottom: $('friend_template').innerHTML.gsub("blank_fid", response[0].uid).gsub("blank_src", response[0].pic).gsub("blank_name", response[0].name)});
	    							  }
					    					
										$('friends_loading').style.display = "none";
					    			 }  
					    		);	
						  break; 
		    		  }
	    		  }
			  }
		  }else
		  {
			$('no_friends').style.display = 'block';
			$('friends_loading').style.display = "none";
		  } 
		});

};

var addRentalCars = function(rentalId, token, profiles){
	var profileIds = profiles.select(function(p){
		if (p.selected){return true;}
	}).collect(function(p){
		return p.value;
	}).join(',');
	if (profileIds.length > 0){
		new Ajax.Request("/admin/rentals/" + rentalId + "/cars", {
			method: 'POST',
			parameters: {
				'authenticity_token': token,
				'profile_ids': profileIds
			}
		})
	}
};

var insertRentalCar = function(id, imgSrc, name, carPath, token){
	Element.insert("cars_container", { 'top': $('car_template').innerHTML.gsub('id_holder', id).gsub('img_src_holder', imgSrc).gsub('name_holder', name).gsub('car_path_holder', carPath).gsub('token_holder', token) })
};

var deleteRentalCar = function(carPath, token){
	if (confirm("Are you sure you want to delete this car?")){
		new Ajax.Request(carPath, {
			method: "POST",
			parameters: {
				'_method': 'delete',
				'authenticity_token': token
			}
		});
	}
};

var map;
var geocoder;
var newLocationMarker;
var locationForm;

var initializeNewLocationMap = function(){
	map = new google.maps.Map($('map_wrapper'), {
		zoom: 6,
		center: new google.maps.LatLng(29, 30),
		mapTypeId: google.maps.MapTypeId.ROADMAP
	});
	geocoder = new google.maps.Geocoder();
	newLocationMarker = new google.maps.Marker({map: map});
	
	locationForm = $('location_form');
	if(!locationForm['location[latitude]'].value.blank() && !locationForm['location[longitude]'].value.blank()){
		placeNewLocationMarker(locationForm['location[latitude]'].value, locationForm['location[longitude]'].value)
	}
	
	google.maps.event.addListener(map, 'click', newLocationMapClickHandler);
};

var placeNewLocationMarker = function(latitude, longitude){
	newLocationMarker.setOptions({position: new google.maps.LatLng(latitude, longitude)});
};

var newLocationMapClickHandler = function(event){
	var latitude = event.latLng.lat();
	var longitude = event.latLng.lng();
	locationForm = $('location_form');
	locationForm['location[latitude]'].value = latitude;
	locationForm['location[longitude]'].value = longitude;
	placeNewLocationMarker(latitude, longitude);
	geocoder.geocode({
		'latLng': event.latLng,
		'language': getCookie("locale") == "ar" ? 'ar' : 'en'
	}, function(results, status){
		if (status == google.maps.GeocoderStatus.OK){
			var address = results[0].formatted_address.split(',');
			address.pop(); //country
			var city = address.pop().strip(); //city
			$$('#location_form option').first().selected = true;
			$$('#location_form option').each(function(option){
				if (option.innerHTML.strip() == city){
					option.selected = true;
					return true;
				}
			});
		}
	});
};

var initializeOffRoadMap = function(){
	map = new google.maps.Map($('map_wrapper'), {
		zoom: 6,
		center: new google.maps.LatLng(29, 30),
		mapTypeId: google.maps.MapTypeId.ROADMAP
	});
	locations.each(function(location){
		new google.maps.Marker({map: map, position: new google.maps.LatLng(location.latitude, location.longitude), title: location.title});
	});
};

var mouseOnSectionsDropdown = false;

var hideSectionsDropdown = function(){
	mouseOnSectionsDropdown = false;
	setTimeout(function(){
		if (!mouseOnSectionsDropdown){
			$('sections_dropdown').style.display = 'none';
		}
	}, 500);
};

var validatePollVote = function(form){
	if (!form.choice[0].checked && !form.choice[1].checked){
		alert("You must choose one of the two choices!!");
		return false;
	}
	if (form.comment.value.blank()){
		alert("You must leave a comment with your vote!!");
		return false;
	}
};

var animationButtonsJustLoaded=true;
var animationButtonsEnabled=true;
var setAnimationButtons = function(lang){
    if (lang=='ar'){
      $('next').className = ($('FrogJSleftThumb1').style.display == 'none') ? 'disabled' : '';
      $('previous').className = ($('FrogJSrightThumb1').style.display == 'none') ? 'disabled' : '';
    }else {
      $('previous').className = ($('FrogJSleftThumb1').style.display == 'none') ? 'disabled' : '';
      $('next').className = ($('FrogJSrightThumb1').style.display == 'none') ? 'disabled' : '';
    }
    animationButtonsEnabled=true;
}

var animateFeaturedCars = function(direction,carsNumber,lang){

  if (animationButtonsJustLoaded){
    if(( lang=='en' && direction == 'previous')||(lang=='ar' && direction=='next')){
      return false;
    } else{
      animationButtonsJustLoaded = false;
    }
  }

  if(!animationButtonsEnabled){
    return false;
  }
  animationButtonsEnabled=false;
	if(direction == "previous"){
    lang == 'ar' ? $('FrogJSrightThumb1').onclick() : $('FrogJSleftThumb1').onclick();
    current -= 1;
	} else {
    lang == 'ar' ? $('FrogJSleftThumb1').onclick() : $('FrogJSrightThumb1').onclick();
    current += 1;
	}
  setTimeout("setAnimationButtons('"+lang+"')",1000);
  return false;
}

jQuery(window).load(function(){
    if($('FrogJS')){
       $('FrogJS').style.visibility = 'visible'; 
    }
    if (getCookie("locale") == "en"){
      if($('previous')) { $('previous').className = 'disabled';}
    }else{
      if($('next')){$('next').className = 'disabled';}
    }
  });


















