loadingimage = '<div align="center"><img src="/images/loading.gif"></div>';

currentreach = 0;
totalreach = 500000;

adtype = 0;

function $_(id) {
	return document.getElementById(id);
}
function ajax() {
	var ro;
	var browser = navigator.appName;
	if(browser == "Microsoft Internet Explorer"){
		ro = new ActiveXObject("Microsoft.XMLHTTP");
	}else{
		ro = new XMLHttpRequest();
	}
	return ro;	
}
function enable(div) {
	$_(div).disabled = false;	
}
function bload(action, subaction, destination, values, callback) {

	if(destination != null) {
		$_(destination).innerHTML = loadingimage;		
	}

	var ajx = new ajax();
	if(values != null) {
		ajx.open('get','/includes/ajax.php?action=' + action + '&subaction=' + subaction + '&' + values.join('&') + '&random=' + Math.random(99999999), true);
	} else {
		ajx.open('get','/includes/ajax.php?action=' + action + '&subaction=' + subaction + '&random=' + Math.random(99999999), true);
	}
	ajx.onreadystatechange = function() {
		if(ajx.readyState == 4) {
			if(destination != null)
				$_(destination).innerHTML = ajx.responseText;
			if(typeof(callback) != 'undefined')
				setTimeout(callback, 10);
		}
	}
	ajx.send(null);
	
}

var loading = '<div style="text-align:center; margin:10px;"><img src="/images/loading/loading.gif" height="32" width="32" alt="loading"></div>';

function morePhotos() {
	$('#more_photos').toggle('show');	
}

function ajax_get(file, parameters, dataCatch, whenDone) {
	if(dataCatch != null) { document.getElementById(dataCatch).innerHTML = loading; }
    var ajx = new ajax;
	ajx.open('get', file + '?' + parameters + '&random=' + Math.random(99999999), true);
    ajx.onreadystatechange = function() {
        if(ajx.readyState == 4) {
			if(dataCatch != null) { document.getElementById(dataCatch).innerHTML = ajx.responseText; }
			if(typeof(whenDone) != 'undefined') { setTimeout(whenDone, 10); }
        }
    }
    ajx.send(null);
}

function ajax_post(file, parameters, dataCatch, whenDone) {
	if(dataCatch != null) { document.getElementById(dataCatch).innerHTML = loading; }
    var ajx = new ajax;
    ajx.open('POST', file, true);
    ajx.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    ajx.setRequestHeader("Content-length", parameters.length);
    ajx.setRequestHeader("Connection", "close");
    ajx.onreadystatechange = function() {
        if(ajx.readyState == 4) {
			if(dataCatch != null) { document.getElementById(dataCatch).innerHTML = ajx.responseText; }
			if(typeof(whenDone) != 'undefined') { setTimeout(whenDone, 10); }
        }
    }
    ajx.send(parameters);
}

fblogout = '';

function update_userbox(name, image, url, logout, userid) {

  bload('login', null, null, ['name=' + name, 'image=' + escape(image), 'id=' + userid, 'logout=' + escape(logout)], 'loggedin()');
  fblogout = logout;
 $('#overlay').animate({'alpha':'toggle'});

}

function loggedin() {
	if(window.location.pathname == "/alerts.php") {
		$_('create_alert').submit();
	} else {
		document.location = '/profile.php?';	
	}
}

function logout() {
	FB.Connect.logoutAndRedirect('/includes/ajax.php?action=logout');
}

function auth_using_fb() {
  //get the users data from FB
  var viewer  = FB.Facebook.apiClient.fql_query(
  
      'SELECT name, pic_square_with_logo, profile_url FROM user WHERE uid='+FB.Facebook.apiClient.get_session().uid,
      
      function(results) {
        update_userbox( results[0].name,
                        results[0].pic_square_with_logo,
                        results[0].profile_url,
                        'FB.Connect.logoutAndRedirect("./index.php");return false;', FB.Facebook.apiClient.get_session().uid)
      }
  );
}

function no_fb() {
		
}

function assignHints() {
	
	$('.hinted').click( function() {
		if($(this).attr('caption') != "") {
			var hinttxt = $(this).attr('caption');
			$('#hint').html(hinttxt);
			$('#hint').fadeIn('slow');
		}
	});
		
}

feature_total = 1;
var feature_array = new Array();

//add a feature when creating an ad
function addFeature() {
	
	var feat = $_('feat_val').value;
	
	if(feat != "") {
		//check if already exitsts
		var exists = false;
		for(i=0; i<feature_array.length; i++) {
			if(feature_array[i] == feat) {
				exists = true;	
			}
		}
		$_('feat_val').value = '';
		
		if(!exists) {
			feature_array.push(feat);
			sfeat = feat.replace(" ","_");
			
			$_('features').innerHTML += '<a href="javascript:deleteFeature(\'' + sfeat + '\');" class="bigbutton" style="width:180px; float:left; clear:none;" id="feat_' + sfeat + '">' + feat + '</a>';
			$_('feature_data').value = feature_array.join(",");
			feature_total++;
		} else {
			alert("You've already entered this feature.");	
		}
		$_('feat_val').focus();
		
	} else {
		alert("You cannot add an empty feature.");	
	}
	
}
//delete a feature when creating an ad
function deleteFeature(id) {
	for(i=0; i<feature_array.length; i++) {
		if(feature_array[i] == id) {
			feature_array.splice(i,1);
		}
	}
	$_('feature_data').value = feature_array.join(",");
	$('#feat_'+id).fadeOut('slow');
	
}

function validate_contactForm() {
		var f = document.getElementById('contactForm');
		var isValid = true;
		if(f.name.value == '') {
			alert("Please enter your name.");
			f.name.focus();
			isValid = false;
		} else if(f.email.value == '' && f.phone.value == '') {
			alert("Please enter your email address or your phone number.");
			f.email.focus();
			isValid = false;
		} else if(f.message.value == '') {
			alert("Please enter a message.");
			f.message.focus();
			isValid = false;
		}
		return isValid;
	}



function select(category, item, active) {
	switch(category) {
		case 'category':
			if($_('icon_' + item).label != 'on') {
				
				$_('basicad').innerHTML = loadingimage;				
				
				switch(item) {
					case 1:
						vshift = -30;
					break;
					case 3:
						vshift = 35;
					break;
					case 2:
						vshift = 100;
					break;					
				}
				
				$("#icon_" + item).animate({"left": "+=475px", "top": "-=" + vshift + "px", "opacity": 1}, "slow");
				$_('icon_' + item).label = 'on';
				$_('largeleft').label = 'shifted';	
				$("#largeleft").animate({"left": "-=475px", "opacity": 1}, "slow");
				$("#basicad").animate({"top": "+=0px"}, "slow", function() { bload('load', item, 'basicad', ['activesession=1'], 'assignHints()'); });
				switch(item) {
					case 1:
						/*$(".subcontainer").animate({"height": "+=1024px"}, "slow");*/
					break;
					case 3:
						$(".subcontainer").animate({"height": "+=665px"}, "slow");
					break;
					case 2:
						$(".subcontainer").animate({"height": "+=665px"}, "slow");
					break;					
				}
				adtype = item;
				$('#hint').html($('#icon_' + item).attr('caption'));
				$('#hint').fadeIn('slow');
				
			} else {

				switch(item) {
					case 1:
						vshift = -30;
					break;
					case 3:
						vshift = 35;
					break;
					case 2:
						vshift = 100;
					break;					
				}
				
				$_('basicad').innerHTML = loadingimage;
				
				$("#icon_" + item).animate({"left": "-=475px", "top": "+=" + vshift + "px", "opacity": 1}, "slow");
				$_('icon_' + item).label = 'off';
				$_('largeleft').label = 'shifted';	
				$("#largeleft").animate({"left": "+=475px", "opacity": 1}, "slow");	
				/*$("#basicad").animate({"top": "-=945px"}, "slow");*/
				switch(item) {
					case 1:
						/*$(".subcontainer").animate({"height": "-=1024px"}, "slow");*/
					break;
					case 3:
						$(".subcontainer").animate({"height": "-=665px"}, "slow");
					break;
					case 2:
						$(".subcontainer").animate({"height": "-=665px"}, "slow");
					break;					
				}
				adtype = 0;
				$('#hint').fadeOut('slow');
				
			}
		break;
		
		case 'product':	
			if(active != 'bypass') {
				placement(item);
			}
			if($_('icon_' + item).label != 'on') {
				$("#icon_" + item).animate({"left": "+=420px", "opacity": 1}, "slow");
				$_('icon_' + item).label = 'on';
				var vol = $("#icon_" + item).attr('alt');
				if(vol) {
					totalreach = parseInt(totalreach) + parseInt(vol);
				}
			} else {
				$("#icon_" + item).animate({"left": "-=420px", "opacity": 1}, "slow");
				$_('icon_' + item).label = 'off';
				var vol = $("#icon_" + item).attr('alt');
				if(vol) {
					totalreach = totalreach - vol;
				}
			}
			checkvolume(category);	
		break;
	}
}
function highlight(category, item) {
	switch(category) {
		case 'product':
			$_('detailbox').style.top = $_('icon_' + item).style.top;
		    $('#detailbox').fadeIn('slow');
		break;
	}
}
function checkFeatures() {
	
	var ajx = new ajax();

	ajx.open('get','includes/ajax.php?action=load&subaction=placement&random=' + Math.random(99999999), true);
	ajx.onreadystatechange = function() {
		if(ajx.readyState == 4) {
			var items = ajx.responseText.split("|");
			for(i=0;i<items.length;i++) {
				setTimeout("select('product'," + items[i] + ", 'bypass')", 5);
			}
		}
	}
	ajx.send(null);
	
}

function checkvolume(category) {
	var ti = 0;
	for(i=1;i<6;i++) {
		if($_('icon_' + i).label == 'on')
			ti++;
	}
	if(ti == 5) {
		$("#largeleft").animate({"left": "-=350px", "opacity": 1}, "slow");
		$("#audience").animate({"left": "-=350px", "opacity": 1}, "slow");
		$_('largeleft').label = 'shifted';	
	} else if($_('largeleft').label == 'shifted' && ti < 5) {
		$("#largeleft").animate({"left": "+=350px", "opacity": 1}, "slow");
		$("#audience").animate({"left": "+=350px", "opacity": 1}, "slow");
		$_('largeleft').label = 'normal';	
	}
}

function stepback(step) {

	if(step>1) {
		document.location = '/ad.php?step=' + (step - 1);
	} else {
		document.location = '/';
	}
}
function stepback_new(step) {
	switch(step) {
		case "ad_general":
			document.location = '/login_register.php';
			break;
		case "ad_photos":
			document.location = '/ad_general.php';
			break;
		case "ad_review":
			document.location = '/ad_photos.php';
			break;
		case "ad_summary":
			document.location = '/ad_review.php';
			break;
	}
}

function deleteAd(id) {

	bload('delete', 'ad', null, ['adid=' + id], null);
	
	$("#ad_" + id).fadeOut('fast');
	$("#del_" + id).fadeOut('fast');
	
	totalads--;
	
	if(totalads < 1) {
		$("#incomplete").html('<h3>You have no incomplete ads.</h3>');
	}

}

function nextstep(step) {
	switch(step) {
		default:
		
			switch(adtype) {
				
				case 1:
					if(validate(step)) {
						$_('form_1').submit();
					}
				break;
				
				case 2:
					if(validate(step)) {
						$_('form_1').submit();
					}				
				break;	
				
				case 3:
					if(validate(step)) {
						$_('form_1').submit();
					}				
				break;
				
				default:
					validate();
				break;
				
			}

		break;
		case '2':
			$_('form_1').submit();
		break;
		case '3':		
			$_('form_1').submit();						
		break;
		case '4':
			$_('form_1').submit();
		break;
	}
}
function nextstep_new(step, adtype) {
	switch(step) {
		case 'ad_photos':
			$_('form_1').submit();
			break;
			
		case 'ad_review':		
			$_('form_1').submit();						
			break;
			
		case 'ad_summary':
			$_('form_1').submit();
			break;
			
		default:
			switch(adtype) {
				case 1:
					if(validate(step)) {
						$_('form_1').submit();
					}
					break;
				
				case 2:
					if(validate(step)) {
						$_('form_1').submit();
					}				
					break;	
				
				case 3:
					if(validate(step)) {
						$_('form_1').submit();
					}				
					break;
				
				default:
					validate();
					break;
				
			}

			break;
	}
}


function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function adjcounter() {
	if(currentreach < totalreach) {
		currentreach = currentreach + ((totalreach - currentreach) * .2);
		$_('aud_vol').innerHTML = addCommas(Math.round(currentreach));
	} else if(currentreach > totalreach) {
		currentreach = currentreach - ((currentreach - totalreach) * .2);
		$_('aud_vol').innerHTML = addCommas(Math.round(currentreach));
	} else {
		$_('aud_vol').innerHTML = addCommas(totalreach);
	}
	setTimeout("adjcounter();", 50);
}

function validate(fields) {
	var errors = 0;
	var errorcopy = '<h3 align="left">You need to correct the following issues to continue:</h3>';
	
	//if(adtype == 0) {
	//	errorcopy += '<li>You have not selected a classified ad type</li>';
	//	errors++;
	//}
	
	$('#form_1 :input').each( function() {
		
		if($(this).attr('required') == '1' && $(this).val() == '') {
			errorcopy += '<li>The field: ' + $(this).attr('name') + ' is required!</li>';
			errors++;	
		}
		
	});
	
	if(errors > 0) {
	
		warning(errorcopy);
		return false;
	
	} else {
		return true;	
	}
	
}

function showLargeImage(path) {
	$('#lrgImageBox').fadeIn("medium");
	$('#lrgImageBox').html("<div align='center'><img src='"+path+"' /><br /><a href='javascript:hideLargeImage();' class='bigbutton nofloat'>CLOSE</a></div>");
	$('#overlay').animate({'alpha':'toggle'});	
}
function hideLargeImage() {
	$('#lrgImageBox').fadeOut("medium");
	$('#overlay').animate({'alpha':'toggle'});
}

function warning(message) {
	
	$('#overlay').animate({'alpha':'toggle'});
	$('#noticebox').fadeIn("fast");
	$('#noticebox').html('<div align="left">' + message + '<br><br><a href="javascript:closeOverlay();" class="bigbutton">OK</a></div>');	
	
}

function closeOverlay() {
	$('#overlay').animate({'alpha':'toggle'});
	$('#noticebox').fadeOut("slow");

}

cropurl = '';

function fileComplete(src, seed) {
	/*$_('fileInputUploader').style.display = 'none';*/
	$_('image_edit').innerHTML = '<img id="cropbox" src="uploads/' + seed + '_upl.jpg?random=' + Math.random(9999999999) + '"/>';
	/*$_('image_edit').style.display = 'block';
	//$_('cropbutton').style.display = "block";
	$_('cropbuttoncancel').style.display = "block";*/
	
	cropurl = 'uploads/' + seed + '_upl.jpg';	
	
	var rodid = Math.random(999999);

	var newsrc = '/includes/ajax.php?action=crop&imgsrc=' + cropurl + '&x=0&y=0&w=0&h=0&roid=' + rodid + '&random=' + Math.random(9999999);
	$_('uploaded_images').innerHTML += '<img class="uploadthumb" src="' + newsrc + '" id="img_' + ttlimg + '" title="' + rodid + '" label="' + ttlimg + '" width="100" height="100" />';	
	tthide();
	ttasign();
	
	/*$('#image_edit').fadeOut('slow');
	//$('#cropbutton').fadeOut('slow');
	$('#cropbuttoncancel').fadeOut('slow');*/
	/*$_('fileInputUploader').style.display = 'block';*/
	ttlimg++;
	
	//cropStart('uploads/' + seed + '_upl.jpg');
}

function updateCoords(c)
{
	jQuery('#x').val(c.x);
	jQuery('#y').val(c.y);
	jQuery('#w').val(c.w);
	jQuery('#h').val(c.h);
};


function cropStart(url) {
	
	cropurl = url;
	
	jQuery(function(){
		jQuery('#cropbox').Jcrop({
			aspectRatio: 1,
			onSelect: updateCoords
		});	
	});
}

ttlimg = 0;

function tthide() {
	$('.qtip').fadeOut('slow');
}

function ttasign() {
	
	$('.uploadthumb').each(function() {
		$(this).qtip({
	
			content: '<a class="smallbutton" href="javascript:delPhoto(' + $(this).attr('label') + ',' + $(this).attr('title') + ');">Delete Photo</a>  <a class="smallbutton" href="javascript:setFeat(' + $(this).attr('label') + ',' + $(this).attr('title') + ');">Set as Featured</a>', // Set the tooltip content to the current corner
			position: {
			  corner: {
				 tooltip: 'bottomMiddle', // Use the corner...
				 target: 'topMiddle' // ...and opposite corner
			  }
			},
			show: 'click',
			hide: 'click', // Don't specify a hide event
			style: {
			  border: {
				 width: 5,
				 radius: 10
			  },
			  padding: 10, 
			  textAlign: 'center',
			  tip: true, // Give it a speech bubble tip with automatic corner detection
			  name: 'cream' // Style it according to the preset 'cream' style
			}
		});		
	});
	
}

function noCrop() {
	
	var rodid = Math.random(999999);

	var newsrc = '/includes/ajax.php?action=crop&imgsrc=' + cropurl + '&x=0&y=0&w=0&h=0&roid=' + rodid + '&random=' + Math.random(9999999);
	$_('uploaded_images').innerHTML += '<img class="uploadthumb" src="' + newsrc + '" id="img_' + ttlimg + '" title="' + rodid + '" label="' + ttlimg + '" width="100" height="100" />';	
	tthide();
	ttasign();
	
	/*$('#image_edit').fadeOut('slow');
	//$('#cropbutton').fadeOut('slow');
	$('#cropbuttoncancel').fadeOut('slow');*/
	/*$_('fileInputUploader').style.display = 'block';*/
	ttlimg++;

}

function loadImages() {

	bload('load', 'images', 'uploaded_images', null, imagesLoaded());

}

function imagesLoaded() {
	setTimeout('ttasign()',500);					 
}

function cropImage() {
	if (parseInt(jQuery('#w').val())<1) {
		warning('Please select a crop region then try again.');
	} else {
		
		var rodid = Math.random(999999);
		
		var newsrc = '/includes/ajax.php?action=crop&imgsrc=' + cropurl + '&x=' + parseInt(jQuery('#x').val()) + '&y=' + parseInt(jQuery('#y').val()) + '&w=' + parseInt(jQuery('#w').val()) + '&h=' + parseInt(jQuery('#h').val()) + '&roid=' + rodid + '&random=' + Math.random(9999999);
		
		$_('uploaded_images').innerHTML += '<img class="uploadthumb" src="' + newsrc + '" id="img_' + ttlimg + '" label="' + ttlimg + '" title="' + rodid + '" width="100" height="100" />';		
		
		tthide();
		ttasign();
		
		$('#image_edit').fadeOut('slow');
		$('#cropbutton').fadeOut('slow');
		$('#cropbuttoncancel').fadeOut('slow');
		$_('fileInputUploader').style.display = 'block';
		ttlimg++;
	}		
}

function delPhoto(id, roid) {
	$('#img_' + id).fadeOut('slow');
	if($('#featured').attr('value') == id) {
		$('#featured').attr('value','')
	}
	
	bload('delete', 'photo', null, ['id=' + roid], null);
	
	tthide();
	ttasign();
	// How do we hide the tooltip?
}

function resetFeature() {
	$('.uploadthumb').removeClass('highlight');	
}

function setFeat(id) {
	resetFeature();
	$('#img_' + id).addClass('highlight');
	tthide();
	ttasign();
	$('#featured').attr('value',id);
	ajax_get('/includes/ajax.php', 'action=photo_setFeatured&id='+id, null, null);
}
function placement(item) {
	bload('feature','placement', null, ['placement=' + item]);	
}
function cropImageCancel() {
	$_('fileInputUploader').style.display = 'block';
	$_('image_edit').style.display = 'none';
	$_('cropbuttoncancel').style.display = 'none';
	$_('cropbutton').style.display = 'none';
}

function empty(id) {
	$_(id).innerHTML = '';
}

function setStatus(id, status, type) {

	switch(status) {
			
		default:
		
			var adcontents = $_('ad_' + id + '_contents').innerHTML;
			
			var el = $_('ad_' + id);
			el.parentNode.removeChild(el);			
			
			var dt = document.createElement("div");
            dt.id = "ad_" + id;
            dt.setAttribute("align","left");
            dt.className ="ad_med";
			
			var cnt = document.createElement("div");
            cnt.setAttribute("align","left");
			cnt.id = "ad_" + id + "_contents";
			cnt.innerHTML = adcontents;
			
			dt.appendChild(cnt)
			
			var opts = document.createElement("div");
            opts.setAttribute("align","left");
            opts.className ="options";
            opts.innerHTML = '<a href="/includes/ajax.php?action=edit&type=ad&id=' + id + '&adtype=1">EDIT</a><a href="javascript:setStatus(\'' + id + '\',\'6\',\'cars\');">DELETE</a><a href="javascript:setStatus(\'' + id + '\',\'1\',\'cars\');">ACTIVATE</a>';
			
            dt.appendChild(opts);	
			
			$_('inactive').appendChild(dt);
			
		break;
		
		case "1":			

			var adcontents = $_('ad_' + id + '_contents').innerHTML;
			
			var el = $_('ad_' + id);
			el.parentNode.removeChild(el);
			
			var dt = document.createElement("div");
            dt.id = "ad_" + id;
            dt.setAttribute("align","left");
            dt.className ="ad_med";
			
			var cnt = document.createElement("div");
            cnt.setAttribute("align","left");
			cnt.id = "ad_" + id + "_contents";
			cnt.innerHTML = adcontents;
			
			dt.appendChild(cnt)
			
			var opts = document.createElement("div");
            opts.setAttribute("align","left");
            opts.className ="options";
			opts.innerHTML = '<a href="/includes/ajax.php?action=edit&type=ad&id=' + id + '&adtype=1">EDIT</a><a href="javascript:setStatus(\'' + id + '\',\'6\',\'cars\');">DELETE</a><a href="javascript:setStatus(\'' + id + '\',\'5\',\'cars\');">DEACTIVATE</a>';                       
			
            dt.appendChild(opts);	
			
			$_('active').appendChild(dt);

		break;
		
		case "6":
		
			var el = $_('ad_' + id);
			el.parentNode.removeChild(el);
		
		break;
		
	}	
	
	bload('update','adstatus', null, ['status=' + status, 'adid=' + id, 'adtype=' + type]);
}

function forceDigits(evt, field) {
	if(document.all){
		if(evt.keyCode < 48 || evt.keyCode > 57){
			if(evt.keyCode != 8 && evt.keycode != 46 && evt.keycode != 188)
				return false;
		}
	} else {
		if(evt.charCode < 48 || evt.charCode > 57){
			if(evt.keyCode != 8 && evt.keycode != 46 && evt.keycode != 188)
				return false;
		}
	}
	
	// auto format
	
}

function focusInputClear(e, defaultString) {
	if(e.value == defaultString) {
		e.value = "";
	}
}
function blurInput(e, defaultString) {
	if(e.value == "") {
		e.value = defaultString;
	}
}
function searches() {
	alert("*development*");	
}

function saveItem(id) {
	saveditems++;
	$_('saveheader').innerHTML = 'Saved Autos (' + saveditems + ')';
	$_('cont_exp').src = '../images/contract.gif';
	$('#searchopts_detail_container').fadeIn('fast');
	bload('save', 'auto', null, ['id='+id], function() { bload('load', 'saved_autos', 'searchopts_detail_container') } );	
	tt('#save', 'Auto Saved','topMiddle');
}
function clearBasket() {
	saveditems = 0;
	$_('saveheader').innerHTML = 'Saved Autos (0)';
	$_('cont_exp').src = '../images/expand.gif';
	$('#searchopts_detail_container').fadeOut('fast');
	bload('delete', 'basket', null, null);	
}
function delItem(id) {
	bload('delete', 'auto', null, ['id='+id], function() { bload('load', 'saved_autos', 'searchopts_detail_container') } );
	saveditems--;
	$_('saveheader').innerHTML = 'Saved Autos (' + saveditems + ')';
}
function expandSave() {
	if($_('searchopts_detail_container').style.display == "none") {
		$_('cont_exp').src = '../images/contract.gif';
		$('#searchopts_detail_container').fadeIn('fast');
		bload('load', 'saved_autos', 'searchopts_detail_container');
	} else {
		$_('cont_exp').src = '../images/expand.gif';
		$('#searchopts_detail_container').fadeOut('fast');	
	}
}
function addCompare(id) {
	if($_('menu_compare_num') != null) {
		$_('menu_compare_num').style.display = "inline";
	}
	var ajx = new ajax();
	ajx.open('get','/includes/ajax.php?action=addCompare&id='+id+'&random=' + Math.random(99999999), true);
	ajx.onreadystatechange = function() {
		if(ajx.readyState == 4) {
			if(ajx.responseText == "not logged in") {
				alert("You must be logged in to compare cars");
			} else if(ajx.responseText == "problem") {
				alert("An error occured while trying to compare this car.  Please try again later.");
			} else if(ajx.responseText != "") {
				if($_('menu_compare_num') != null) {
					$_('menu_compare_num').innerHTML = ajx.responseText;
				}
				var s = '';
				if(ajx.responseText > 1)
					s = 's';
				tt('#comp', ajx.responseText + ' Car' + s + ' to Compare','topMiddle');
				compareTotal++;
			} else {
				tt('#comp', 'You are already comparing this car.','topMiddle');
			}
		}
	}
	ajx.send(null);
}
function tt(item, contents, top) {
	
		$(item).qtip({
	
			content: '<div style="color:#333;" id="tip_content">' + contents + '</div>', // Set the tooltip content to the current corner
			position: {
			  corner: {
				 tooltip: top, // Use the corner...
				 target: 'bottomMiddle' // ...and opposite corner
			  }
			},
			show: {
                  when: false, // Don't specify a show event
                  ready: true // Show the tooltip when ready
			},
			hide: {
					when: 'unfocus'
				},
			style: {
			  border: {
				 width: 5,
				 radius: 10
			  },
			  padding: 10, 
			  textAlign: 'center',
			  tip: true, // Give it a speech bubble tip with automatic corner detection
			  name: 'cream' // Style it according to the preset 'cream' style
			}
		});		
	
}
function rtt(item, contents, top) {
	
		$(item).qtip({
	
			content: '<div style="color:#333;" id="tip_content">' + contents + '</div>', // Set the tooltip content to the current corner
			position: {
			  corner: {
				 tooltip: top, // Use the corner...
				 target: 'top' // ...and opposite corner
			  }
			},
			show: {
                  when: false, // Don't specify a show event
                  ready: true // Show the tooltip when ready
			},
			hide: {
					when: 'unfocus'
				},
			style: {
			  border: {
				 width: 5,
				 radius: 10
			  },
			  padding: 10, 
			  textAlign: 'center',
			  tip: true, // Give it a speech bubble tip with automatic corner detection
			  name: 'cream' // Style it according to the preset 'cream' style
			}
		});		
	
}
function newhomespreview(item, contents, top) {
	
		$(item).qtip({
	
			content: '<div style="color:#333;" id="tip_content" align="left">' + contents + '</div>', // Set the tooltip content to the current corner
			position: 'bottomLeft',
			show: {
                  when: false, // Don't specify a show event
                  ready: true // Show the tooltip when ready
			},
			hide: {
					fixed: true
				},
			style: {
			  border: {
				 width: 2,
				 radius: 5
			  },
			  width: 650,
			  padding: 10, 
			  textAlign: 'left',
			  tip: false, // Give it a speech bubble tip with automatic corner detection
			  name: 'cream' // Style it according to the preset 'cream' style
			}
		});		
	
}

function setOption(type) {
	if($_(type + '_alert').value == '0') {
		$_(type).style.backgroundPosition = "top";
		$_(type + '_alert').value = '1';
	} else {
		$_(type + '_alert').value = '0';
		$_(type).style.backgroundPosition = "bottom";
	}
}
function showAlert(id) {
	bload('load', 'alert_view', 'alert_view', ['alertid='+id]);
}
function txt2phone(id, dealer, gocode, vin) {
	if(dealer) {
		tt('#txt2p', '<iframe src="http://www.gumiyo.com/mq.p?a=sp&vin=' + gocode + '+' + vin + '&shortcode=801411" width="230" height="120" frameborder="0"></iframe>', 'topMiddle');
		ajax_post('/includes/ajax.php', 'action=track_txt&type=auto&id='+id, null, null);
		
	} else {
		tt('#txt2p', 'Phone:&nbsp;<input type="text" id="phone_no" style="width:80px; padding:5px;">&nbsp;<a href="javascript:pulltxtdata(' + id + ');" class="smallbutton">Go</a>', 'topMiddle');
	}
}
function emailFriend(id) {
	tt('#emailphone', 'Email:&nbsp;<input type="text" id="email_addy" style="width:80px; padding:5px;">&nbsp;<a href="javascript:pullemldata(' + id + ');" class="smallbutton">Go</a>', 'topMiddle');
}
function pulltxtdata(id) {

	var phone = $_('phone_no').value;
	if(phone.length < 8 && phone != 'undefined') {
		alert("Please enter a valid phone number.");
		return;
	}
	
	$_('tip_content').innerHTML = 'Sending Text Message....';
	var ajx = new ajax();
	ajx.open('get','/includes/ajax.php?action=load&subaction=txtcar&id=' + id + '&random=' + Math.random(999999999), true);
	ajx.onreadystatechange = function() {
		if(ajx.readyState == 4) {
			txtsend(ajx.responseText, phone, id);
		}
	}
	ajx.send(null);
}

function pullemldata(id) {

	var email = $_('email_addy').value;
	if(email == 'undefined') {
		alert("Please enter a valid Email Address.");
		return;
	}

	$_('tip_content').innerHTML = 'Email Message Sent Successfully.';
	var ajx = new ajax();
	ajx.open('get','/includes/ajax.php?action=load&subaction=emailcar&id=' + id + '&email=' + email + '&random=' + Math.random(999999999), true);
	ajx.onreadystatechange = function() {
		if(ajx.readyState == 4) {
			//$_('tip_content').innerHTML = 'Email Message Sent Successfully.';
		}
	}
	ajx.send(null);
}

function txtsend(message, phone, id) {
	ajax_post('../includes/ajax.php', 'action=track_txt&type=auto&id='+id, null, null); //tracks the text
	
	var ajx = new ajax();
	ajx.open('get','http://txt.mediaoneutah.com/includes/forcesend.php?sender=' + phone + '&msg=' + message, true);
	ajx.onreadystatechange = function() {
		if(ajx.readyState == 4) {
			$_('tip_content').innerHTML = 'Text Message Sent Successfully.';		
		}
	}
	ajx.send(null);
}

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);
}

function loadAlertModels(value) {
	bload('load','model', 'model_view',['model='+value]);	
}

function alertLogin() {
	var user = $_('username_login').value;
	var pass = $_('password_login').value;
	bload('login_alerts', '', 'login_options', ['username='+user,'password='+pass], "alertLoginValidate()");
}
function alertLoginValidate() {
	if($_('valid_login').value == 1) {
		$_('create_alert').submit();
	} else {
		FB.init('98bb47e8066f33198877942e45394dab', 'xd_receiver.htm');
	}
}
function alertRegisterSubmit() {
	var user = 	$_('username_reg').value;
	var email = $_('email_reg').value;
	var pwd = 	$_('pwd_reg').value;
	var ver = 	$_('ver_reg').value;
	var code = 	$_('code_reg').value;
	
	bload('load', 'registrationsubmit', 'login_options', ['username='+user,'password='+pwd,'email='+email,'vpassword='+ver,'code='+code], "alertRegisterValidate()");
}
function alertRegisterValidate() {
	if($_('valid_reg').value == 1) {
		$_('create_alert').submit();
	} else {
		FB.init('98bb47e8066f33198877942e45394dab', 'xd_receiver.htm');
	}		
}
function dealer(action) {
	switch(action) {
		
		case "ads":
			$_('results').style.display = "block";
			$_('sortBar').style.display = "block";
			if($_('pagingBox'))
				$_('pagingBox').style.display = "block";
			$_('itemsPerPage').style.display = "block";
			$_('dealer_contact').style.display = "none";			
			break;
		
		case "profile":
			$_('results').style.display = "none";
			$_('sortBar').style.display = "none";
			if($_('pagingBox'))
				$_('pagingBox').style.display = "none";
			$_('itemsPerPage').style.display = "none";			
			$_('dealer_contact').style.display = "none";			
			break;
		
		case "contact":
			$_('results').style.display = "none";
			$_('sortBar').style.display = "none";
			if($_('pagingBox'))
				$_('pagingBox').style.display = "none";
			$_('itemsPerPage').style.display = "none";				
			$_('dealer_contact').style.display = "block";			
			break;		
		
	}
}
function setTab(tab) {
	
	$('#statistics_tab').removeClass('at');
	$('#expired_tab').removeClass('at');
	$('#alerts_tab').removeClass('at');
	$('#messages_tab').removeClass('at');
	$('#settings_tab').removeClass('at');
	$('#ad_tab').removeClass('at');
	
	if(!tab)
		tab = 'ad';
		
	$('#' + tab + '_tab').addClass('at');
	
}
function setDealerTab(tab) {
	
	$('#contact_tab').removeClass('at');
	$('#profile_tab').removeClass('at');
	$('#ad_tab').removeClass('at');
	
	if(!tab)
		tab = 'ad';
		
	$('#' + tab + '_tab').addClass('at');
	
}

function showPhone(car, owner, ownerType) {
	document.getElementById('btn_phoneNumber').style.display = "none";
	document.getElementById('phoneNumber').style.display = "inline";
	var values = new Array('id='+car, 'type=auto', 'owner='+owner, 'owner_type='+ownerType);
	bload('showPhoneNumber', null, null, values, null);
}


function sendDealerContact(page) {
	var f = document.contactForm;
	var name = f.cname.value;
	var phone = f.cphone.value;
	var zip = f.czip.value;
	var email = f.cemail.value;
	var time = f.ctime.value;
	var trade = f.ctrade.value;
	var payment = f.cdown.value;
	var financing = f.cfinancing.value;
	var message = f.cmessage.value;	
	var offers = f.coffers.value;
	var dealer = f.cdealer.value;
	if(page == "car") {
		var new_used = f.cnew_or_used.value;
		var make = f.cmake.value;
		var model = f.cmodel.value;
		var vin = f.cvin.value;
		var year = f.cyear.value;
		var price = f.cprice.value;
	} else {
		var new_used = null;
		var make = null;
		var model = null;
		var vin = null;
		var year = null;
		var price = null;
	}
	if(name == "" || name == "your name here") {
		alert("Please enter your name.");
		f.cname.focus();
	} else if(email == "" || email == "your email here") {
		alert("Please enter your email address.");
		f.cemail.focus();
	} else {
		//bload('processDealerContact', null, null, ['name='+name,'phone='+phone,'zip='+zip,'email='+email,'time='+time,'trade='+trade,'payment='+payment,'financing='+financing,'message='+message,'dealer='+dealer,'offers='+offers,'new_used='+new_used,'make='+make,'model='+model,'vin='+vin,'year='+year,'price='+price], null);	
		
		if(page == "car") {
			$_('contactSeller').innerHTML = '<div align="center"><br /><br /><br /><br /><b>Sending the email...</b><br /><br /><img src="/images/loading/bar1.gif" alt="loading" /><br /><br /><br /><br /></div>';
		} else {
			$_('dealer_contact').innerHTML = '<div align="center"><br /><br /><br /><br /><b>Sending the email...</b><br /><br /><img src="/images/loading/bar1.gif" alt="loading" /><br /><br /><br /><br /></div>';	
		}
		
		var parameters = 'action=processDealerContact&name='+name+'&phone='+phone+'&zip='+zip+'&email='+email+'&time='+time+'&trade='+trade+'&payment='+payment+'&financing='+financing+'&message='+message+'&dealer='+dealer+'&offers='+offers+'&new_used='+new_used+'&make='+make+'&model='+model+'&vin='+vin+'&year='+year+'&price='+price+'&random=' + Math.random(999999999);
		var ajx = new ajax;
		ajx.open('POST', "/includes/ajax.php", true);
		ajx.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		ajx.setRequestHeader("Content-length", parameters.length);
		ajx.setRequestHeader("Connection", "close");
		ajx.onreadystatechange = function() {
			if(ajx.readyState == 4) {
				if(ajx.responseText == "sent") {
					if(page == "car") {
						$_('contactSeller').innerHTML = '<div align="center"><p><br><br><br><br><a class="grey_button"> Message Sent. </a><br><br><br><br></p></div>';
					} else {
						$_('dealer_contact').innerHTML = '<div align="center"><p><br><br><br><br><a class="grey_button"> Message Sent. </a><br><br><br><br></p></div>';	
					}
				} else if(ajx.responseText == "notsent") {
				//} else {
					if(page == "car") {
						$_('contactSeller').innerHTML = '<div align="center"><p><br><br><br><br><a class="grey_button"> Message could not be sent.</a><br><br><br><br></p></div>';
						$_('contactSeller').innerHTML += '<div style="display:none;">'+ajx.responseText+'</div>';
						//$_('contactSeller').innerHTML = '<div align="center"><p><br><br><br><br><a class="grey_button"> Message could not be sent. ('+ajx.responseText+')</a><br><br><br><br></p></div>';
					} else {
						$_('dealer_contact').innerHTML = '<div align="center"><p><br><br><br><br><a class="grey_button"> Message could not be sent.</a><br><br><br><br></p></div>';
						$_('dealer_contact').innerHTML += '<div style="display:none;">'+ajx.responseText+'</div>';
						//$_('dealer_contact').innerHTML = '<div align="center"><p><br><br><br><br><a class="grey_button"> Message could not be sent. ('+ajx.responseText+')</a><br><br><br><br></p></div>';	
					}
				}
			}
		}
		ajx.send(parameters);		
	}
}

function checkMakeDropdown(model) {
	var makeDropdown = document.getElementById('select_make');
	var selectedMake = makeDropdown.options[makeDropdown.selectedIndex].value;
	if(selectedMake != "") {
		getModels(selectedMake, model);
	} else {
		document.getElementById('select_models').style.display = "block";	
	}
}


function alert_delete(id) {
	if(confirm("Are you sure you want to delete this alert?")) {
		document.location = '/profile.php?page=alerts&action=delete&id='+id;
	}
}



function getModels(make, model) {
	//model is used to make one selected (if previously selected by user)
	if(make != "") {
		document.getElementById('select_models').style.display = "none";
		document.getElementById('model_loading').style.display = "block";
		var ajx = new ajax;
		ajx.open('get', '/includes/ajax_cars.php?action=get_models&make='+make+'&random='+Math.random(99999));
		ajx.onreadystatechange = function() {
			if(ajx.readyState == 4) {
				if(ajx.responseText != '') {
					var models = ajx.responseText;
					models = models.split("||");
					var modelOptions = "<option value=''>Select a model</option>";
					for(var i in models) {
						modelInfo = models[i].split("|");
						modelId = modelInfo[0];
						modelName = modelInfo[1];
						modelOptions += "<option value='"+modelId+"'";
						if(model == modelId) {
							modelOptions += " selected";	
						}
						modelOptions += ">"+modelName+"</option>";
					}
					document.getElementById('model_display').innerHTML = '<select id="select_models" name="model" class="med padding_tiny">'+modelOptions+'</select">';
					document.getElementById('model_loading').style.display = "none";
					document.getElementById('select_models').style.display = "block";
				} else {
					alert("There was an error retrieving the models.");
				}
			}
		}
		ajx.send(null);
	}
}

function rotate() {
	$('#slideshow1').cycle();
}

function report(id) {
	alert("This auto has been reported and will reviewed by our staff. Thank you!");
	var ajx = new ajax;
	ajx.open('get', '/includes/ajax_cars.php?action=report&id='+id+'&random='+Math.random(99999));
	ajx.onreadystatechange = function() {
		// sent
	}
	ajx.send(null);
}
function adLoader(src, tgt) {
	if (navigator.userAgent.indexOf('Netscape') > -1 && navigator.userAgent.indexOf('Netscape/8') == -1 && navigator.userAgent.indexOf('OS X') == -1) {
		if ((document.getElementById) && navigator.userAgent.indexOf('Netscape6') == -1) {
			var dgTgt = document.getElementById(tgt);
			if (dgTgt!=null) {
				var dgSrc = document.getElementById(src);
				dgTgt.innerHTML = dgSrc.innerHTML;
			}
		}
	} else {
		if (document.getElementById && document.createElement) {
			if (navigator.userAgent.indexOf('Mac_PowerPC') == -1) {
				var dgTgt = document.getElementById(tgt);
				if (dgTgt!=null) {
					var tgtCh = document.createElement("div");
					var dgSrc = document.getElementById(src);
					var temp = dgTgt.appendChild(tgtCh);
					var moveIt = dgTgt.replaceChild(dgSrc, temp);
					dgSrc.style.display="block";
				}
			}
		}
	}
}
