var new_freecap = function(){
	// loads new freecap image
	if(document.getElementById){
		// extract image name from image source (i.e. cut off ?randomness)
		thesrc = $("freecap").src;
		thesrc = thesrc.substring(0,thesrc.lastIndexOf(".")+4);
		// add ?(random) to prevent caching
		$("freecap").src = thesrc+"?"+Math.round(Math.random()*100000);
	} 
	else {
		alert("Sorry, cannot autoreload freecap image\nSubmit the form and a new freecap will be loaded");
	}
};

var setFocus = function(element){
	try{
		$(element).focus();	
	}
	catch(err){
		// alert(err.description);
	}
};

var add2Fav = function(){
	var getData = 'action=ADD&view='+$F('adId');
	var ajaxFav = new Ajax.Request('userfavoritesXML.php',{method: 'get', parameters: getData, onComplete: favResponse});
};

var favResponse = function(request){
	alert(request.responseText);
};

var showFriend = function(){
	Effect.toggle('tell_friend_form', 'blind');
};

var checkFriendForm = function(){
	if ($F('nameFriend') == '') {
		alert('Please enter your name');
		setFocus('nameFriend');
		return(false);
	}
	if ($F('emailFriend') == '') {
		alert('Please enter a valid email address');
		setFocus('emailFriend');
		return(false);
	}
	
	if ($F('friendnameFriend') == '') {
		alert('Please enter your friend\'s name');
		setFocus('friendnameFriend');
		return(false);
	}
	if ($F('friendemailFriend') == '') {
		alert('Please enter a valid email address for your friend');
		setFocus('friendemailFriend');
		return(false);
	}
	if ($F('messageFriend') == '') {
		alert('Please enter a message');
		setFocus('messageFriend');
		return (false);
	}
	
	validemail=0;
	var checkStr = $F('emailFriend');
	for (i = 0; i < checkStr.length; i++){
		if(checkStr.charAt(i)=="@")
			validemail |= 1;
		if(checkStr.charAt(i)==".")
			validemail |= 2;
	}
	if(validemail != 3){
		alert('Please enter a valid email address');
		setFocus('emailFriend');
		return (false);
	}
	return true;
};

var makeRequestTellFriend = function(){
	if(checkFriendForm()){
		var postData = 'name='+$F('nameFriend')+'&email='+$F('emailFriend')+'&message='+$F('messageFriend')+'&friendemail='+$F('friendemailFriend')+'&friendname='+$F('friendnameFriend')+'&listingid='+$F('vehicleFriend')+'&mode='+$F('modeFriend');
		ajax =  new Ajax.Updater('tell_friend_form', 'friendmailXML.php',{method:'post', parameters:postData, onFailure: reportError, onLoading: showLoader('friend_loader'), onSuccess: hideLoader('friend_loader')});
	}
	return false;
}

var checkContactForm = function() {
	//alert(document.getElementById('name').value);
	if ($F('name') == '') {
		alert('Please enter your name');
		setFocus('name');
		return(false);
	}
	if ($F('email') == '') {
		alert('Please enter a valid email address');
		setFocus('email');
		return(false);
	}
	/**if ($F('word') == '') {
		alert('Please enter the word');
		setFocus('word');
		return(false);
	}*/
	validemail=0;
	var checkStr = $F('email');
	for (i = 0; i < checkStr.length; i++){
		if(checkStr.charAt(i)=="@")
			validemail |= 1;
		if(checkStr.charAt(i)==".")
			validemail |= 2;
	}
	if(validemail != 3){
		alert('Please enter a valid email address');
		setFocus('email');
		return (false);
	}
	if ($F('message') == '') {
		alert('Please enter your message');
		setFocus('message');
		return (false);
	}
	return true;
};

var makeRequestContact = function(){
	if(checkContactForm()){
		new Effect.Highlight('contact_content',{startcolor:'#E8EEFA', endcolor:'#ffffff', duration: 10});
		$('dummy_contact_form').disable();
		//var postData = 'name='+$F('name')+'&email='+$F('email')+'&message='+$F('message')+'&word='+$F('word')+'&captcha='+$F('captcha')+'&ownerid='+$F('owner')+'&listingid='+$F('vehicle')+'&mode='+$F('mode');
		var postData = 'name='+$F('name')+'&email='+$F('email')+'&message='+$F('message')+'&ownerid='+$F('owner')+'&listingid='+$F('vehicle')+'&mode='+$F('mode');
		ajax =  new Ajax.Updater('contact_content', 'contactXML.php',{method:'post', parameters:postData, onFailure: reportError, onLoading: showLoader('contact_loader'), onSuccess: hideLoader('contact_loader')});
	}
	return false;
};

var reportError = function(){
	alert('An error has occurred, please try again later.');
};

var showLoader = function(element){
	$(element).src = 'http://img.servihoo.com/revolution/classifieds/loader.gif';
	$(element).style.display = 'block';
};

var hideLoader = function(element){
	$(element).style.display = 'none';
};

var checkLoginForm = function(){
	if ($F('username') == '') {
		alert('Please enter your username');
		setFocus('username');
		return (false);
	}
	if ($F('password') == '') {
		alert('Please enter your password');
		setFocus('password');
		return (false);
	}
};

var showterms = function(){
	newwin=window.open("terms.php","Terms","menubar=no, scrollbars=yes, width=420, height=380, directories=no,location=no,resizable=yes,status=no,toolbar=no");
};

var checkForgotPasswordForm = function() {
	if ($F('email') == '') {
		alert('Please enter your email address');
		setFocus('email');
		return(false);
	}
};

var MM_goToURL = function() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
};

var RollIt = {
    timeout : null,
    showPopup : function(element){
        clearTimeout(this.timeout);
        if($(element).style.display == 'none'){
            this.timeout = setTimeout(function(){new Effect.SlideDown(element, {duration:.3, fps:40})},400);
        }
    },
    hidePopup : function(element){
        if($(element).style.display == 'none'){
            clearTimeout(this.timeout);
        }else{
            this.timeout = setTimeout(function(){new Effect.SlideUp(element, {duration:.3, fps:40})},300);
        }
    }    
};

var MM_openBrWindow = function(theURL,winName,features) { //v2.0
	  window.open(theURL,winName,features);
};

var observeSearchBox = function(){
	Event.observe('searchtoptext', 'keypress', function(event){
												if(event.keyCode == 13){
													$('search_top_form').submit();
												}
											}
	);
};

/**
*	Fonction pour la recherche des annonces
*	@param int intervale L'intervale entre la date d'aujourdhui pour la recherche des annonces
*/
var recherche = function(intervale){
	document.location.href='searchresults.php?intervale='+intervale+'&type='+$F('categoryIDSearch')+'&Submit=Search';
};

var toggleCalendar = function(){
	Effect.toggle('rowCalendrier', 'blind');
};

var	checkDog = function(){
	if($F('section') == 74){
		new Effect.Appear('mspca_notice');
	}
	else{
		if($('mspca_notice').style.display == ''){
			new Effect.Fade('mspca_notice');
		}
	}
};

var showSmsNotification=function(){
	Effect.toggle('smsNotificationForm', 'blind');
};

var expand = function(element, elementParent){
	if ($(element).style.display == "") {
 		Effect.BlindUp(element, {duration: 1.0});
		//$(elementParent).style.backgroundImage= "url(images/block-arrow-collapsed.gif)";
	} else {
 		Effect.BlindDown(element, {duration: 1.0});
		//$(elementParent).style.backgroundImage= "url(images/block-arrow-expanded.gif)";
	}
};

var Cookie = {
  set: function(name, value, daysToExpire) {
    var expire = '';
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
    }
    return (document.cookie = escape(name) + '=' + escape(value || '') + expire);
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  accept: function() {
    if (typeof navigator.cookieEnabled == 'boolean') {
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1');
    return (Cookie.erase('_test') === '1');
  }
};

var deleteReply = function(id){
	var confirmation = confirm("Are you sure you want to delete this reply ?");
	if(confirmation){
		document.location.href = 'inbox.php?action=delete&id='+id;
	}
};
