/*
 * ADS.JS
 *
 * Provides utility functions for the display of ads.
 *
 * aug 17 2006, MA Hartman: created the file.
 * sep 06 2006, MA Hartman: reconstructed the file.
 * sep 13 2006, MA Hartman: added ad gallery functionality.
 * sep 15 2006, MA Hartman: added ad placement functionality.
 * sep 19 2006, MA Hartman: adapted for PHP sessions.
 */


/*
 * When a user clicks on an ad, display the full ad.
 */
function click_ad(aid, sid, q)
{
	 window.location = 'index.php?csid='+sid+'&task=show_ad&aid='+aid;
}
function edit_ad(aid, sid, q)
{
	 window.location = 'index.php?csid='+sid+'&task=edit_ad&aid='+aid;
}

function place_new_ad(sid)
{
    window.location = 'index.php?csid='+sid+'&task=new_ad';
}

function ad_search(sid, task)
{
    var sf = document.getElementById('search_field');
	if(sf.value != ''){
    window.location = 'index.php?csid='+sid+'&task=show_ads&from='+task+'&stype=simple&q='+sf.value;
	}
	else {
    window.location = 'index.php?task=clear_search_data';
	}
}
function ad_searchfield_keypress(e, sid, task){
	var keynum = 0;
	if(window.event){ // IE
		keynum = e.keyCode
	}else if(e.which){ // Netscape/Firefox/Opera
		keynum = e.which
	}
	if(keynum == "13") ad_search(sid, task);
}
/*
 * Set the big ad picture to the pic picture.
 */
function set_as_big(pic, descr)
{
	var temp = '<img id=\"big_picture_img\" src=""/><span id=\"big_picture_descr\"></span>';
	document.getElementById('big_picture').innerHTML = temp; 
	document.getElementById('big_picture_img').src = pic;    
    document.getElementById('big_picture_descr').innerHTML = descr;
}

function showVideo(data) 
{
	document.getElementById('big_picture').innerHTML = '&nbsp;'+data; 
}


function hidediv(id) {
	//safe function to hide an element with a specified id
	if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).style.display = 'none';
	}
	else {
		if (document.layers) { // Netscape 4
			document.id.display = 'none';
		}
		else { // IE 4
			document.all.id.style.display = 'none';
		}
	}
}

function showdiv(id) {
	//safe function to show an element with a specified id
		  
	if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).style.display = 'block';
	}
	else {
		if (document.layers) { // Netscape 4
			document.id.display = 'block';
		}
		else { // IE 4
			document.all.id.style.display = 'block';
		}
	}
}
/*
 * Set the ad as a favorite
 */
function toggle_favorite(sid, aid, registered)
{
	if(registered == 0){
		var message = REGISTERED_USERS_ONLY;
		alert(message);
	}
	else{
	    var star = document.getElementById('favo_star');
	    var favo_link = document.getElementById('favorite_link');
	    var add = (favo_link.getAttribute('fav') == 0) ? 1 : 0;

	    // Show a busy icon:
	    show_star();

	    // Set up an AJAX transaction:
	    xmlHttp = GetXmlHttpObject();
	    if (xmlHttp != null) {
	        var url = "ajax/ad.php?task=set_favorite&csid="+sid+"&aid="+aid+"&add="+add+"&entropy="+Math.random();
	        xmlHttp.onreadystatechange = function()
	        {
	            if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {

	                if (xmlHttp.responseText == 'added') {
						star.src = 'images/icons/star.png';
						favo_link.setAttribute('fav', '1');
	                    favo_link.innerHTML = REMOVE_FROM_FAVORITES;
	                    hide_star();
	                }
	                else if (xmlHttp.responseText == 'removed') {
						star.src = 'images/icons/star_gray.png';
						favo_link.setAttribute('fav', '0');
	                    favo_link.innerHTML = ADD_TO_FAVORITES;
	                    hide_star();
	                }
	                else { // Failure;
	                    hide_star();
	                }
	            }
	        }
	        xmlHttp.open("GET", url, true);
	        xmlHttp.send(null);
	    }
	    return false; // Prevent reload
	}
}

/*
 * Report a bad ad. An email is sent to a designated address.
 */
function report_bad_ad(sid, aid, mcid)
{
	if(document.getElementById('bad_container'))
		return false;

    var report_link = document.getElementById('report_link');

	show_star();

	xmlHttp = GetXmlHttpObject();
    if (xmlHttp != null) {
        var url = "ajax/ad.php?task=fetch_bad_ad&csid="+sid+"&aid="+aid+"&mcid="+mcid+"&entropy="+Math.random();

        xmlHttp.onreadystatechange = function()
        {
            if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
				var container = document.createElement('div');
				container.setAttribute('id', 'bad_container');
				container.className = 'bad_container';

				document.body.appendChild(container);

				document.getElementById('bad_container').style.left = ((document.body['offsetWidth'] / 2) - (document.getElementById('bad_container').offsetWidth / 2)) + 'px';

                document.getElementById('bad_container').innerHTML = xmlHttp.responseText;
				hide_star();
            }
        }
        xmlHttp.open("GET", url, true);
        xmlHttp.send(null);
    }

    return false; // Prevent reload
}

var hide_report_bad_ad = function () {
	document.body.removeChild(document.getElementById('bad_container'));
}

var send_bad_ad_report = function (sid, aid, mcid) {
	var reason = document.getElementById('bad_reason').value;
	var message = document.getElementById('bad_info').value;

	if(reason == 0) {
		document.getElementById('bad_reason').style.border = '1px #d75b5b solid';
		document.getElementById('bad_reason').focus();
		return;
	}
	else if(reason == 'Other' && message == '') {
		document.getElementById('bad_reason').style.border = '1px #a5acb2 solid';
		document.getElementById('bad_info').style.border = '1px #d75b5b solid';
		document.getElementById('bad_info').focus();
		return;
	}

	message = message.replace(/</g, '<-');
	message = message.replace(/>/g, '->');
	message = message.replace(/\n/g, '<br />');
	message = message.replace(/'/g, '`');
	//message = message.replace(/"/g, '`');

	document.getElementById('send_report').disabled = true;
	document.getElementById('cancel_report').disabled = true;

	xmlHttp = GetXmlHttpObject();
    if (xmlHttp != null) {
        var url = "ajax/ad.php?task=report_bad_ad&csid="+sid+"&aid="+aid+"&mcid="+mcid+"&entropy="+Math.random()+"&reason="+reason+"&message="+message;

        xmlHttp.onreadystatechange = function()
        {
            if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {

				hide_report_bad_ad();
            }
        }
        xmlHttp.open("GET", url, true);
        xmlHttp.send(null);
    }
}

/*
 * Show the send-friend textbox:
 */
function show_friend(nheight)
{
	var el = document.getElementById('user_info_div');
	var height = el.style.height;
	height = height.replace('px', '');
	height = eval(height);

	if(!nheight) {
		nheight = 70;
	}

    var box = document.getElementById('friend_box');
    if (box.style.display == 'none') {
        box.style.display = 'block';
		el.style.height = (height + nheight) + 'px';
    }
    else {
        box.style.display = 'none';
		el.style.height = (height - nheight) + 'px';
    }
    return false;
}

/*
 * Show the contact owner textbox:
 */
function show_owner(nheight)
{
	var el = document.getElementById('user_info_div');
	var height = el.style.height;
	height = height.replace('px', '');
	height = eval(height);

	if(!nheight) {
		nheight = 67;
	}

    var box = document.getElementById('owner_box');
    if (box.style.display == 'none') {
        box.style.display = 'block';
		el.style.height = (height + nheight) + 'px';
    }
    else {
        box.style.display = 'none';
		el.style.height = (height - nheight) + 'px';
    }
    return false;
}
/*
 * Send a message to the ad owner
 */
function send_to_owner(sid, aid, message)
{
	if(document.getElementById('owner_box_message').value ==  message | trim(document.getElementById('owner_box_message').value) == '') { // ! TODO : of bericht ( talen )
		return;
	}
    // Show a busy icon:
	show_star();

	if(!check_email(document.getElementById('contact_email').value)) {
		alert('Not a valid email address!');
		return false;
	}
		
	// Set up an AJAX transaction:
    xmlHttp = GetXmlHttpObject();
    if (xmlHttp != null) {
    	var pmess = encodeURI(document.getElementById('owner_box_message').value);
    	var email = document.getElementById('contact_email').value;
    	if(pmess==MESSAGE) pmess = '';
        var url = "ajax/ad.php?task=send_to_owner&csid="+sid+"&aid="+aid+"&email="+email+"&pmess="+pmess+"&entropy="+Math.random();
        //alert(url);
        xmlHttp.onreadystatechange = function()
        {
            if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
              	if(xmlHttp.responseText == '1') {	// Mail sent
					$msg = '<img src="images/icons/email_go.png"> <b>'+MAIL_SENT+'</b>';
				}
				else {
					$msg = '<img src="images/icons/email_error.png"> <b style="color: red">'+MAIL_ERROR+'</b>';
				}

				show_owner(56);

				document.getElementById('email_msg').style.display = 'block';
				document.getElementById('email_msg').innerHTML = $msg;

                document.getElementById('owner_box_message').value = MESSAGE;
				hide_star();
            }
        }
        xmlHttp.open("GET", url, true);
        xmlHttp.send(null);
    }
    return false; // Prevent reload
}
/*
 * Send the ad to a friend
 */
function send_to_friend(sid, aid)
{
	var toMail    = document.getElementById('friend_mail').value;
	var toName    = document.getElementById('friend_name').value;
	var fromMail  = document.getElementById('sender_mail').value;
	var fromName  = document.getElementById('sender_name').value;
    var pmess     = encodeURI(document.getElementById('friend_box_message').value);

    
    if(!check_email(toMail)) {
		alert('Friends email is not a valid email address!');
		return false;
	}
    
	if(!check_email(fromMail)) {
		alert('Your email is not a valid email address!');
		return false;
	}
    
    if(pmess == MESSAGE | pmess == '') {
    	alert('Please check your message.')
		return;
	}
    // Show a busy icon:
    show_star();

    // Set up an AJAX transaction:
    xmlHttp = GetXmlHttpObject();
    if (xmlHttp != null) {
    	var url = "ajax/ad.php?task=send_to_friend&csid="+sid+"&aid="+aid+"&toMail="+toMail+"&toName="+toName+"&fromMail="+fromMail+"&fromName="+fromName+"&pmess="+pmess+"&entropy="+Math.random();
        xmlHttp.onreadystatechange = function()
        {
            if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
              	//if(xmlHttp.responseText == '1') {	// Mail sent
              	if(true) {
              		$msg = '<img src="images/icons/email_go.png"><b>'+MAIL_SENT+'</b>';
				}
				else {
					$msg = '<img src="images/icons/email_error.png"> <b style="color: red">'+MAIL_ERROR+'</b>';
				}

				show_friend(45);

				document.getElementById('email_f_msg').style.display = 'block';
				document.getElementById('email_f_msg').innerHTML = $msg;

                document.getElementById('friend_box_message').value = MESSAGE;
				hide_star();
            }
        }
        xmlHttp.open("GET", url, true);
        xmlHttp.send(null);
    }
    return false; // Prevent reload
}

/*
 * Add media box
 */
function add_media_box()
{
    // Retrieve the number of added media:
    var num_media = parseInt(document.new_ad_form.num_media.value);
    if(num_media <= 4) {



    // Build media box:
    var media_box = document.createElement('div');
    media_box.className = 'optional';
    media_box.id = 'media_box_'+num_media;

    var l = document.createElement('label');
    l.htmlFor = 'media_image_'+num_media;
    //l.appendChild(document.createTextNode('Add pictures '+(num_media + 1)+':'));
    l.appendChild(document.createTextNode(LOCATION_OF_IMAGE+' '+(num_media + 1)+':'));
    media_box.appendChild(l);


    var m = document.createElement('input');
    m.type = 'file';
    m.name = 'media_image_'+num_media;
    m.id = 'media_image_'+num_media;
    m.className = 'inputFile';
    m.title = SELECT_FILE;
    media_box.appendChild(m);

    /*var d = document.createElement('input');
    d.type = 'text';
    d.name = 'media_descr_'+num_media;
    d.id = 'media_descr_'+num_media;
    d.className = 'inputText';
    d.title = 'Add a description here';
    media_box.appendChild(d);*/

    document.getElementById('main_ad_fieldset').insertBefore(media_box, document.getElementById('add_media_link'));

    document.getElementById('media_box_'+num_media).appendChild(document.createElement('br'), document.getElementById('add_media_link'));
	document.getElementById('media_box_'+num_media).appendChild(document.createElement('br'), document.getElementById('add_media_link'));

    // Increment the number of added media:
    document.new_ad_form.num_media.value = (num_media + 1);

	var newHeight = document.getElementById('mediaSpacer').style.height;
	newHeight = newHeight.replace('px', '');
	newHeight = eval(newHeight);

	document.getElementById('mediaSpacer').style.height = (newHeight + 30) + 'px';
    }
}

function fixed_media_boxes () {
	var num_media_ = parseInt(document.new_ad_form.num_media.value);
	var parent_id = document.getElementById('main_ad_fieldset');

	if(num_media_ <= 4) {
		for(i=0; i<5; i++) {
			var child_id = document.getElementById('media_box_'+i);
			if(child_id) {
				parent_id.removeChild(child_id);
				document.new_ad_form.num_media.value--;
			}
		}

		for(i=0; i<5; i++) {
			add_media_box();
		}
	}
}

/*
 * Remove all selected favorites
 */
function remove_favorites(sid)
{
   if(!confirm(CONFIRM_DELETE))
	   return;

   show_star();
   var table = document.getElementById('ad_cond2');
   var cbox = table.getElementsByTagName('input');
   for (i = 0; i < cbox.length; i++) {
       if (cbox[i].name != 'remove_favorites' && cbox[i].checked) {
           var aid = cbox[i].name.split('_')[2];
           var row = document.getElementById('ad_'+aid);
           row.style.display = 'none';
           cbox[i].checked = false;
           // Set up an AJAX transaction:

           xmlHttp = GetXmlHttpObject();
           if (xmlHttp != null) {
               var url = "ajax/ad.php?task=set_favorite&csid="+sid+"&aid="+aid+"&add=0&entropy="+Math.random();

               xmlHttp.onreadystatechange = function()
               {
                   if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
                       hide_star();
                   }
               }
               xmlHttp.open("GET", url, true);
               xmlHttp.send(null);
           }
       }
   }

   hide_star();
}

/*
 * Toggle the color of an entire row
 */
function toggle_row(el, on)
{
	if(on == 'on') {
		el.style.backgroundColor = '#fde88f';
		el.style.cursor = 'pointer';
	}
	else {
		el.style.backgroundColor = '#fff';
		el.style.cursor = 'default';
	}
}

/*
 * Remove all selected my ads.
 */
function remove_my_ads(sid)
{
   if(!confirm(CONFIRM_DELETE))
	   return;

   show_star();
   var table = document.getElementById('ad_cond');
   var cbox = table.getElementsByTagName('input');
   var allObjId = '';
   for (i = 0; i < cbox.length; i++) {
       if (cbox[i].name != 'remove_mine' && cbox[i].checked) {
           var aid = cbox[i].name.split('_')[2];
		   allObjId += aid + ',';
       }
   }

   // Remove last comma
   allObjId = allObjId.substring(0, (allObjId.length - 1));

   // Set up an AJAX transaction:

   xmlHttp = GetXmlHttpObject();
   if (xmlHttp != null) {
	   var url = "ajax/ad.php?task=remove_ad&csid="+sid+"&aid="+allObjId+"&entropy="+Math.random();

	   xmlHttp.onreadystatechange = function()
	   {
		   if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
			   for (i = 0; i < cbox.length; i++) {
				   if (cbox[i].name != 'remove_mine' && cbox[i].checked) {
					   var aid = cbox[i].name.split('_')[2];
					   var row = document.getElementById('my_ad_'+aid);
					   row.style.display = 'none';
					   cbox[i].checked = false;
				   }
			   }

			   hide_star();
		   }
	   }
	   xmlHttp.open("GET", url, true);
	   xmlHttp.send(null);
   }

   hide_star();
}

/*
 * Open up the menu item that is clicked on.
 * Subcategories wil be retrieved and set in place.
 */

var xopen = 0;
var m = 0;
function open_left_menu(lmenu_elem,lmenu_mcid,lmenu_request,lmenu_type,lmenu_rid)
{
if(m != lmenu_elem) {
m = lmenu_elem;
xopen = 0;
}
		xopen++;
		//alert("m:" + m + "open" + open);
		var count=0;

	for (var i = 1; i <= 6; i++) {
        var elem = document.getElementById('menu_'+i);
        if (i == parseInt(lmenu_elem)) { // expand this menu:


			// clear all menu items
			var e = elem.getElementsByTagName('ul');
            for (x = 0; x < e.length; x++) {
                elem.removeChild(e[x]);
            }

			if(xopen % 2 == 0) {
				break;
			}
			// create ul beneath it:
            var ul = document.createElement('ul');
            ul.className = 'sublevel';
            elem.appendChild(ul);

            // set up an AJAX call for the subcategories:
            xmlHttp = GetXmlHttpObject();
           if (xmlHttp != null) {
			   if (lmenu_request == 'country') {
               		var url = "ajax/ad.php?task=get_regions&mcid="+lmenu_mcid+"&cid="+lmenu_rid+"&type="+lmenu_type;
               		//alert('url' + url);

			   }

			   else if (lmenu_request == 'brand') {

				   	var url = "ajax/ad.php?task=get_brands&mcid="+lmenu_mcid+"&rid="+lmenu_rid+"&type="+lmenu_type;
			   }

			   xmlHttp.onreadystatechange = function()
               {
                   if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {

					   values = xmlHttp.responseText.split(',');
                       for (var j = 0; j + 1 < values.length; j += 2) {
							   if (lmenu_request == 'country') {
							  		append_li_node(ul, 'index.php?task=show_ads&mcid='+lmenu_mcid+'&rid='+values[j+1], values[j]);
									//alert('index.php?mcid='+lmenu_mcid+'&rid='+values[j+1]+ values[j]);
									count++;
							   }

							   else if (lmenu_request == 'brand') {
								   	append_li_node(ul, 'index.php?task=show_ads&mcid='+lmenu_mcid+'&cid='+values[j+1], values[j]); 						//alert('index.php?mcid='+lmenu_mcid+'&rid='+values[j+1]+ values[j]);
									count++;
							   }



                       }
					   if(count == 0) {
						   append_li_node(ul, '', 'no items yet...');
					   }
                   }
               }
               xmlHttp.open("GET", url, true);
               xmlHttp.send(null);
           }

        }
        else { // Remove the submenu:
            var e = elem.getElementsByTagName('ul');
            for (x = 0; x < e.length; x++) {
                elem.removeChild(e[x]);
            }
        }
    }
    return true;
}

/*
 * Append a full-blown LI element with A tag to where:
 */
function append_li_node(where, href, text)
{
    var li = document.createElement('li');
    var a = document.createElement('a');
    a.href = href;
    a.innerHTML = text;
    li.appendChild(a);
    where.appendChild(li);
}
/*
 * Check form for required fields
 * Added by BJ ter Kuile on 2006-10-04
 * Adapted by Jochen van Wylick on 2006-11-10
 * Adapted by Jochen van Wylick on 2008-04-24
 */
function submit_ad(){
	var errorstr 	= '';
	var spacer 		= '\n\t';

	// Title is empty
	if(document.getElementById('ad_name').value == '')
		errorstr = errorstr + spacer + TITLE_REQUIRED;

	// Description field is empty
	if(document.getElementById('ad_description').value == '')
		errorstr = errorstr + spacer + DESCRIPTION_REQUIRED;

	// Year is not like YYYY
	if(!document.getElementById('ad_year').value.match(/^\d\d\d\d$/))
		errorstr = errorstr + spacer + YEAR_INVALID;

	// Price does not just contain digits
	if(document.getElementById('ad_price').disabled == false && !document.getElementById('ad_price').value.match(/^\d*$/)) {
		errorstr = errorstr + spacer + PRICE_INVALID;
	}
	
	// Price field is empty
	if(document.getElementById('ad_price').disabled == false && document.getElementById('ad_price').value == '') {
		errorstr = errorstr + spacer + PRICE_INVALID;
	}
	
	

	// Alert user and show errors
	if(errorstr!=''){
		errorstr = PLEASE_CHECK_DATA+errorstr;
		alert(errorstr);
		return false;
	}
	//document.getElementById('star').style.display = 'block';
	menu = document.getElementById('loading_frame');
	document.new_ad_form.submit();

	if(menu) {
	  	theTop = Math.round(document.body['offsetHeight'] / 2);
		frame_overlay();
		movemenu();
	}

	document.new_ad_form.submit();
}

function aotw_newprice(){
	var weeks = document.getElementById('num_weeks').value;
	var total = document.getElementById('weekprice').innerHTML*weeks;
	document.getElementById('paypal_quantity').value = weeks;
	document.getElementById('paypal_return').value = document.getElementById('paypal_return').value.replace(/weeks=\d{0,3}/, "weeks="+weeks);
	document.getElementById('totalprice').innerHTML = total;
}

/*
 * This function makes shure that if the price type NOT amount
 * then the price field is empty and locked
 * Created by Jochen van Wylick on 2006-11-10
 */

function check_amount(amountString) {
	if(document.getElementById('ad_price_type').value != amountString) {
		document.getElementById('ad_price').value = PRICE_NO_AMOUNT;
		document.getElementById('ad_price').disabled = true;
		document.getElementById('ad_currency').disabled = true;
	}
	else {
		document.getElementById('ad_price').disabled = false;
		document.getElementById('ad_currency').disabled = false;
		document.getElementById('ad_price').value = '';
		document.getElementById('ad_price').focus();


	}
}
function clear_field(field) {
	field.value = '';
	return;
}

function prod_cat_change() {
	var category = document.getElementById('ad_mcid');
	var field = document.getElementById('ad_category');
	if(category.value== '3') {
		field.style.visibility = 'hidden';
	}
	else {
		field.style.visibility= 'visible';
	}

}

/*
 *
 */
var menu;
var theTop;

function movemenu()
{
	if (window.innerHeight)
	{
		  pos = window.pageYOffset
	}
	else if (document.documentElement && document.documentElement.scrollTop)
	{
		pos = document.documentElement.scrollTop
	}
	else if (document.body)
	{
		  pos = document.body.scrollTop
	}

	pos += (Math.round(document.body['offsetHeight'] / 2) - 50);
	menu.style.top = pos+'px';

	old = pos;
	temp = setTimeout('movemenu()', 500);
}

var frame_overlay = function () {
	var over = document.createElement('div');
	over.setAttribute('id', 'frame_overlay');
	over.className = 'frame_overlay';


	if (document.all)
        var height = document.body.offsetHeight;
    else if (document.layers)
        var height = document.body.document.height;
	else
        var height = document.height;

	over.style.height = (height + 300) + 'px';
	document.body.appendChild(over);
}

var remove_single_media = function (el, csid, amid, aid) {
	if(!confirm(CONFIRM_DELETE))
		return;

	document.getElementById('i_frame').src = "iframe.php?csid="+csid+"&task=remove_single_ad&amid="+amid+"&aid="+aid;
}

var check_select_val = function (el) {
	if(el.value == 0) {
		el.value = 888;
	}
}

var typeOfAd = function (el, csid, mcid) {
	var val = el.value;
	if(getVar('task') == 'doAdvancedSearch') {
		var adType = getVar('s_ad_type');
		var currentLocation = window.location;
		//alert(currentLocation.replace('s_ad_type='+adType,'s_ad_type='+val));
		var p = new RegExp('\='+adType);
		window.location = currentLocation.search.replace(p,"="+val);
		return;
	}
	if(val == 0) {
		window.location = 'index.php?mcid='+mcid+'&csid='+csid+'&sort=post_date&next_sort_order=desc&task=show_ads&type=-1&rid=-1&cid=-1';
	}
	else {
		window.location = 'index.php?mcid='+mcid+'&csid='+csid+'&sort=post_date&next_sort_order=desc&task=show_ads&type='+val+'&rid=-1&cid=-1';
	}
}

function trim(value) {
  value = value.replace(/^\s+/,''); 
  value = value.replace(/\s+$/,'');
  return value;
}

function check_email(str) {
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   //alert("Invalid E-mail ID")
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   //alert("Invalid E-mail ID")
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    //alert("Invalid E-mail ID")
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    //alert("Invalid E-mail ID")
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    //alert("Invalid E-mail ID")
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    //alert("Invalid E-mail ID")
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    //alert("Invalid E-mail ID")
		    return false
		 }

 		 return true					
}


function ToggleAdvancedSearch(value) {
	document.getElementById('s_ad_priceType').disabled = value;
	document.getElementById('s_ad_price').disabled = !value;
	document.getElementById('s_ad_currency').disabled = !value;	
	document.getElementById('includeNonAmounts').disabled = !value;
	
	if(value)
		document.getElementById('s_ad_priceType').value = -1;
	else
		document.getElementById('s_ad_price').value = '';
	return;
}

function checkSearchData() {
	var selectedPriceType = document.getElementById('s_ad_priceType').value;
	var selectedPrice = document.form.s_ad_amount_or_type[1].checked;	
	if(selectedPriceType == -1 && selectedPrice) {
		alert(PLEASE_SELECT_PRICE_TYPE);
		return false;
	}
	else {
		return true;
	}
	
}

function getVar(name)
         {
         get_string = document.location.search;         
         return_value = '';
         
         do { //This loop is made to catch all instances of any get variable.
            name_index = get_string.indexOf(name + '=');
            
            if(name_index != -1)
              {
              get_string = get_string.substr(name_index + name.length + 1, get_string.length - name_index);
              
              end_of_value = get_string.indexOf('&');
              if(end_of_value != -1)                
                value = get_string.substr(0, end_of_value);                
              else                
                value = get_string;                
                
              if(return_value == '' || value == '')
                 return_value += value;
              else
                 return_value += ', ' + value;
              }
            } while(name_index != -1)
            
         //Restores all the blank spaces.
         space = return_value.indexOf('+');
         while(space != -1)
              { 
              return_value = return_value.substr(0, space) + ' ' + 
              return_value.substr(space + 1, return_value.length);
							 
              space = return_value.indexOf('+');
              }
          
         return(return_value);        
         }
function returnToAdvancedSearch() {
	var currentLocation = window.location;
	//alert(currentLocation.replace('s_ad_type='+adType,'s_ad_type='+val));
	var p = new RegExp('\=doAdvancedSearch');
	window.location = currentLocation.search.replace(p,"=search&type=advanced");
}