var delete_comment_control_interval = 0;
var delete_comment_slide_interval = 0;
var countdown_interval = null;

function setSelectionRange(input_id, selectionStart, selectionEnd) {
	var input = document.getElementById(input_id);
	
	if(input.setSelectionRange) {
		input.focus();
		input.setSelectionRange(selectionStart, selectionEnd);
	} else if (input.createTextRange) {
	    var range = input.createTextRange();
    	range.collapse(true);
	    range.moveEnd('character', selectionEnd);
    	range.moveStart('character', selectionStart);
	    range.select();
	};
};

function setCaretToPos (input_id, pos) {
	setSelectionRange(input_id, pos, pos);
};

//slideshow that loads images as it gets ready to show that slide!
function loadNext(selector,images,prev,stopAnim,isCombat){
	if(images.length){
		//figure out which image to show
		var $show=$(selector);
		var curSlide=$show.attr("data-slide");
		var curPlay=$show.attr("data-play");
		if(!curSlide) curSlide=0;
		curSlide=parseInt(curSlide);
		//back to start if too long
		if(curSlide+1>=images.length) curSlide=0;
		//only do anything if the slideshow is ready
		if(!stopAnim || !$show.children().first().hasClass("loading")){
			//go backwards if requested
			if(prev){
				curSlide-=4;
				if(curSlide<0) curSlide=images.length+curSlide;
			}
			//stop auto increment if the user clicked on a control
			if(stopAnim && curPlay!="stop"){
				clearInterval(curPlay);
				$show.attr("data-play","stop");
			}
			//show loading animation if the user clicked a control
			if(stopAnim) $show.children().first().addClass("loading");
			
			//preload the new images
			var tempImg1=$("<img/>")[0];
			$(tempImg1).load(function(){ 
				//first image is loaded
				var tempImg2=$("<img/>")[0];
				$(tempImg2).load(function(){
					//second image is loaded
					//change out the images!
					$show.children().first().fadeOut(500,function(){
						var newHtml='<li class="clear show_next"><a href="'+images[curSlide][0]+'" title="'+images[curSlide][1]+'"><img src="'+images[curSlide][2]+'" alt="'+images[curSlide][3]+'"></a><a href="'+images[curSlide+1][0]+'" title="'+images[curSlide+1][1]+'"><img src="'+images[curSlide+1][2]+'" alt="'+images[curSlide+1][3]+'"></a></li>';
						if(isCombat){
							newHtml='<li class="clear show_next"><a href="'+images[curSlide][0]+'" title="'+images[curSlide][1]+'"><img src="'+images[curSlide][2]+'" alt="'+images[curSlide][3]+'"></a><a href="'+images[curSlide+1][0]+'" title="'+images[curSlide+1][1]+'"><img src="'+images[curSlide+1][2]+'" alt="'+images[curSlide+1][3]+'"></a></li>';
						}
						$show.append(newHtml).children(".show_next").first().hide().fadeIn(500,function(){
							$(this).removeClass("show_next");
							$(this).siblings().first().remove();
					
					
							//set the next slide
							if(curSlide+2>images.length-1) curSlide=-2;
							$show.attr("data-slide",curSlide+2);
					

						});
					});
				});
				tempImg2.src=images[curSlide+1][2];
			});
			tempImg1.src=images[curSlide][2];
		}
	}else{
		//no images in the slideshow, hide the loading animation
		$(selector).children().first().removeClass("loading");
	}
}

function initRecentVehicles(){
	jQuery('#recent_vehicles').attr("data-play",setInterval("loadNext('#recent_vehicles',recent_vehicles,false,false,true)",5000));
	loadNext('#recent_vehicles',recent_vehicles);
	//setup click events for the controls
	$("#recent_vehicles_previous").click(function(){
		loadNext('#recent_vehicles',recent_vehicles,true,true,true);
	});
	$("#recent_vehicles_next").click(function(){
		loadNext('#recent_vehicles',recent_vehicles,false,true,true);
	});
}


// -----------------------------------------------------------------------------------
jQuery(document).ready(function() { //	START DOCUMENT READY
//------------------------------------------------------------------------------------
	
	//try to fix price tag on classifieds
	var priceTag=jQuery('.module h2.price');
	if(priceTag.length){
		priceTag.css({'position':'relative'});
		priceTag.css({'position':'absolute'});
	}
	
	//only resize divs if all the images have loaded!
	jQuery(document).load(function(){
		equalHeight(jQuery('.box.style_05 .box_body'));
	});
	
	// -----------------------------------------------------------------------------------
	// BIND EXTERNAL LINKS
	//------------------------------------------------------------------------------------
	jQuery('a.out').live('click', function(e) {
		e.preventDefault();
		window.open(this.href);
	});
	
    /*
	// -----------------------------------------------------------------------------------
	// ODD CHILD : ADD ODD CLASS / EVEN CHILD : ADD EVEN CLASS
	//------------------------------------------------------------------------------------
	jQuery("ul li:odd").addClass("odd");
	jQuery("ul li:even").addClass("even");
	*/
	/* Disabled 100823 by Ben to use gallery that loads as it goes
	$('#recently_added_photos').cycle({
		timeout:	5000,
		prev:		'#recently_added_photos_previous',
		next:		'#recently_added_photos_next',
		pause:		true
	});
	*/
	//initialize recently added photos slideshow
	/*if(jQuery('#recently_added_photos').length){
		jQuery('#recently_added_photos').attr("data-play",setInterval("loadNext('#recently_added_photos',recently_added_photos)",5000));
		loadNext('#recently_added_photos',recently_added_photos);
		//setup click events for the controls
		$("#recently_added_photos_previous").click(function(){
			loadNext('#recently_added_photos',recently_added_photos,true,true);
		});
		$("#recently_added_photos_next").click(function(){
			loadNext('#recently_added_photos',recently_added_photos,false,true);
		});
	}*/
	//initialize recently added car combats slideshow
	if(jQuery('#recent_car_combats').length){
		jQuery('#recent_car_combats').attr("data-play",setInterval("loadNext('#recent_car_combats',recent_car_combats)",5000));
		loadNext('#recent_car_combats',recent_car_combats);
		//setup click events for the controls
		$("#recent_car_combats_previous").click(function(){
			loadNext('#recent_car_combats',recent_car_combats,true,true);
		});
		$("#recent_car_combats_next").click(function(){
			loadNext('#recent_car_combats',recent_car_combats,false,true);
		});
	}

	//initialize recent_car_combats slideshow
	if(jQuery('#recent_vehicles').length){
		//delay this slideshow
		setTimeout("initRecentVehicles()",2500);
	}
	/*
	$('#recent_car_combats').cycle({
		timeout:	5000,
		prev:		'#recent_car_combats_previous',
		next:		'#recent_car_combats_next',
		pause:		true,
		delay:		2500
	});*/
	
	$('.comment_ticker_wrapper').vTicker({
		speed: 1500,
		pause: 6000,
		showItems: 3,
		mousePause: true,
		height: 199,
		direction: 'up'
		});

	// -----------------------------------------------------------------------------------
	// COLORBOX
	//------------------------------------------------------------------------------------
	doColorBox();
	
	// -----------------------------------------------------------------------------------
	// INITIALIZE -- DROPLET
	//------------------------------------------------------------------------------------
	jQuery('#sort-results select').droplet();
	
	// -----------------------------------------------------------------------------------
	// COLORBOX
	//------------------------------------------------------------------------------------
	jQuery("tr.compare_more").toggle('blind',{},0);
	
	// Collapse all text taht should be
	// jQuery('.expander').expander();

	// View more comments
	jQuery('a[id$="comment_view_more"]').live('click', function() {
		p	= jQuery(this).attr('rel').split('|');

		mvi = p[0];
		mt	= p[1] == undefined ? '' : p[1];
		mti	= p[2] == undefined ? '' : p[2];

		jQuery.getJSON(http_host+'modules/content/ajax/get-more-comments.php', { mvi: mvi, mt: mt, mti: mti, cc: jQuery('span#'+((mt == '')?'':mt+'_')+'comment_showing').html() }, function(data) {
			if(data.comments == undefined) {
				jQuery('#'+((mt == '')?'':mt+'_')+'comment_view_more').hide();
				return false;
			}

			if(data.comments.length == 0) {
				jQuery('#'+((mt == '')?'':mt+'_')+'comment_view_more').hide();
				return false;
			}

			for(var i=0; i<data.comments.length; ++i) {
				var cmt = '';
				if(member_id > 0 && member_id == data.comments[i].member_id) {
					cmt += '<div class="overlay"><a href="javascript:void(0);" rel="'+data.comments[i].comment_id+'" class="list_item_delete">Delete</a></div>';
				}

				cmt += '<img src="'+data.comments[i].member_image.small+'" alt="Avatar" class="avatar">';
				cmt += '<p><span class="date">Posted on: '+data.comments[i].created_date+'</span>, by <span class="author">'+data.comments[i].user_name+'</span></p>';
				cmt += '<p>'+data.comments[i].comment+'</p>';
				cmt += '<span class="clear"></span>';

				jQuery('ul#'+((mt == '')?'':mt+'_')+'comments').append('<li>'+cmt+'</li>');
			}

			jQuery('span#'+((mt == '')?'':mt+'_')+'comment_showing').html(parseInt(jQuery('span#'+((mt == '')?'':mt+'_')+'comment_showing').html()) + data.comments.length);

			if(data.no_more == true) {
				jQuery('#'+((mt == '')?'':mt+'_')+'comment_view_more').hide();
			}

			//reinitialize scroll boxes
			/* var scroll_boxes=jQuery("div.scroll_container"); */
			/* if(scroll_boxes.length){scroll_boxes.scrollbar();}; */

			return false;
		});
	});

	// -----------------------------------------------------------------------------------
	// ADVANCED SEARCH VEHICLE TYPE SELECTION
	// -----------------------------------------------------------------------------------
	jQuery('form[name="search"]').find('select[name="vehicle_type"]').bind('change', function() {
		var manu_field	= jQuery('form[name="search"]').find('select[name="manufacturer"]');
		var model_field	= jQuery('form[name="search"]').find('select[name="model"]');

		manu_field.replaceWith('<select tabindex="'+manu_field.attr('tabindex')+'" name="manufacturer" id="'+manu_field.attr('id')+'" title="Vehicle Make" class="select medium"></select>');
		model_field.replaceWith('<select tabindex="'+model_field.attr('tabindex')+'" name="model" id="'+model_field.attr('id')+'" title="Vehicle Model" class="select medium"><option value="">Select Make</option></select>');

		loadVehicleManufacturers('form[name="search"]');

		/* Dont use manu_field from above, bind doesnt happen*/
		jQuery('form[name="search"]').find('select[name="manufacturer"]').bind('change', function() {
			loadVehicleModels('form[name="search"]');
		});

		/* Dont use manu_field from above, focus doesnt happen*/
		jQuery('form[name="search"]').find('select[name="manufacturer"]').focus();
	});

	// -----------------------------------------------------------------------------------
	// ADVANCED SEARCH MANUFACTURER SELECTION + MODEL POULATION
	//------------------------------------------------------------------------------------
	jQuery('form[name="search"]').find('select[name="manufacturer"]').bind('change', function() {
		loadVehicleModels('form[name="search"]');		
		return true;
	});
	
	// -----------------------------------------------------------------------------------
	// SET UP SITE SEARCH
	//------------------------------------------------------------------------------------
	jQuery('form[name="quick_search"]').bind('submit', function() {
		jQuery("#search_box", this).attr('value', jQuery("#search_box", this).attr('value') == 'Search' ? '' : jQuery("#search_box", this).attr('value'));
	});
	
	inputBlur('form[name="quick_search"] #search_box', 'Search');
	
	jQuery('#adv_search_btn, a.close_advanced_search').click(toggleAdvSearch);
	

	// initialize the search primary color picker
	/*
	var primary_color = jQuery('ul.primary_color');
	if(primary_color.length){
		primary_color.children().click(colorClick);
		jQuery('.primary_color_clear').click(colorClear);
	};
	*/
	jQuery('ul.primary_color li').live('click', colorClick);
	jQuery('.primary_color_clear').live('click', colorClear);
	
	
	
	
	// -----------------------------------------------------------------------------------
	// INITIALIZE -- COUNTDOWN
	//------------------------------------------------------------------------------------
	if(jQuery('.timer .time').length > 0) {
		countdown_interval = setInterval('countdown()', 1000);
	};
	
	
	// -----------------------------------------------------------------------------------
	// INITIALIZE -- ENTER HOVER / EXIT HOVER
	//------------------------------------------------------------------------------------
	jQuery('#header .navigation li, #global .navigation li').mouseover(enterHover).mouseout(exitHover);
	// -----------------------------------------------------------------------------------
	// FIREFOX GLITCH FIX 
	// hover class does not remove from li when mouse leaves over onto an input
	//------------------------------------------------------------------------------------
	jQuery("input").live("mouseenter", function(){
		jQuery(".hover").removeClass("hover");
	});
	
	// -----------------------------------------------------------------------------------
	// VEHICLE NAVIGATION EFFECTS
	//------------------------------------------------------------------------------------
	jQuery(".showroom_vehicle_navigation").each(function(){
		// hover for li
		jQuery(this).children("li")
		.bind("mouseover", function() {
			jQuery(this).addClass("hover").children("a").stop().stop().fadeTo("fast", 1);
		}).bind("mouseout", function(){
			jQuery(this).removeClass("hover").children("a").fadeTo("slow", 0.25);
		});
		// fade out li's that dont have .hover
		jQuery(this).bind("mouseenter", function(){
			jQuery(this).children("li").not(".hover").children("a").fadeTo("fast", 0.25);
		}).bind("mouseleave", function(){
			jQuery(this).find("a").stop().stop().fadeTo("slow", 1);
		});
	});
	
	// -----------------------------------------------------------------------------------
	// INITIALIZE -- SET OPACITY
	//------------------------------------------------------------------------------------
	setOpacity();
	

	// -----------------------------------------------------------------------------------
	// BIND TO ALL CLOSE BUTTONS 
	// -----------------------------------------------------------------------------------
	jQuery('a.button.close').live('click', function(e) { 
		e.preventDefault();
		jQuery.fn.colorbox.close();
	});
	
	// -----------------------------------------------------------------------------------
	// SETUP BLOG POST BUTTON
	// -----------------------------------------------------------------------------------
	jQuery('a.blog_details').live('click', function(e) {
		e.preventDefault();

		if(this.rel == '') { 
			return false;
		};

		loadColorBox(http_host+'blog/details.html?post_id='+this.rel);
	});
	
	// -----------------------------------------------------------------------------------
	// SETUP CAR COMBAT BUTTON + CHANGE VEHICLE BUTTON
	// -----------------------------------------------------------------------------------
	jQuery('a.challenge_to_car_combat, a.challenge_combat, a.button.challenge_now, a.button.choose_combat_vehicle, a.change_vehicle, a.challenge_now_large, a.challenge_cc').live('click', function(e) {
		e.preventDefault();

		if(this.rel == '') {
			return;
		};

		loadColorBox(http_host+'car-combat/popup-challenge.html?mvi='+this.rel+'&pt='+build_push_to());
	});

	// -----------------------------------------------------------------------------------
	// SETUP CAR COMBAT STEP 1 BUTTON 
	// -----------------------------------------------------------------------------------
	jQuery('a.verify_challenge').live('click', function(e) {
		e.preventDefault();

		if(jQuery('input[name="challenger_mvi"]:checked').attr('value') == undefined) {
			setStatus('Select a vehicle to continue', 'fail', '.car_combat_challenge .content');
		} else if(jQuery('input[name="defender_mvi"]').attr('value') == '') {
			setStatus('Invalid defender vehicle selection', 'fail', '.car_combat_challenge .content');
		} else {
			loadColorBox(http_host+'car-combat/popup-challenge-verify.html?challenger_mvi='+jQuery('input[name="challenger_mvi"]:checked').attr('value')+'&defender_mvi='+jQuery('input[name="defender_mvi"]').attr('value'));
		};
	});

	// -----------------------------------------------------------------------------------
	// SETUP CAR COMBAT STEP 2 BUTTON 
	// -----------------------------------------------------------------------------------
	jQuery('a.send_challenge').live('click', function(e) {
		e.preventDefault();
		showLoading();

		jQuery('input[name="smack_talk"]').attr('value', ((jQuery('input[name="smack_talk"]').attr('value').substr(0, 4) != 'ex: ') ? jQuery('input[name="smack_talk"]').attr('value') : ''));

		jQuery.getJSON(http_host+'car-combat/popup-challenge-verify.html?post&'+jQuery('#module_colorbox form').serialize(), function(data, status) {
			if(status != 'success') {
				setStatus('There was an error contacting the server. Please try again.', 'fail', '.car_combat_challenge .content:eq(0)');
				hideLoading();
			} else if(data.status == 'fail') {
				setStatus(data.message, 'fail', '.car_combat_challenge .content:eq(0)');
				hideLoading();
			} else {
				loadColorBox(http_host+'car-combat/popup-challenge-verify.html?complete='+data.extra+'&'+jQuery('#module_colorbox form').serialize());
			}
		});
	});

	// -----------------------------------------------------------------------------------
	// SETUP SEND A MESSAGE BUTTONS
	// -----------------------------------------------------------------------------------
	jQuery('a.button.send_a_message, a.button.contact_owner, a.send_owner_a_message, a.button_msg').bind('click', function(e) {
		e.preventDefault();

		if(this.rel == '') {
			return;
		};

		loadColorBox(http_host+'popup-send-message.html?member_id='+this.rel+'&pt='+build_push_to());
	});

	// -----------------------------------------------------------------------------------
	// SETUP FRIEND REQUEST BUTTONS
	// -----------------------------------------------------------------------------------
	jQuery('a.button.add_as_friend, a.button_add').bind('click', function(e) {
		e.preventDefault();

		if(this.rel == '') {
			return;
		};

		loadColorBox(http_host+'popup-friend-request.html?member_id='+this.rel+'&pt='+build_push_to());
	});

	// -----------------------------------------------------------------------------------
	// SETUP FRIEND REQUEST CONFIRM BUTTONS && SETUP FRIEND ACCEPT REQUEST ON SEND REQUEST POPUP
	// -----------------------------------------------------------------------------------
	jQuery('a.button.send_request, a.button.accept.on_request').live('click', function(e) {
		e.preventDefault();

		if(this.rel == '') {
			return;
		};

		showLoading();

		jQuery.getJSON(http_host+'popup-friend-request.html?submit&member_id='+this.rel, function(d, s) {
			if(s != 'success') {
				setStatus('Failed to connect to server.', 'fail');
				hideLoading();
				return false;
			};
	
			if(d.status == 'pass') {
				jQuery('a.button.cancel').removeClass('left').removeClass('cancel').addClass('close').html('Close');
				jQuery('a.button.send_request').remove();
				jQuery('a.button.accept.on_request').remove();
				jQuery('h5.message').remove();
			};
	
			setStatus(d.message, d.status);
			hideLoading();
		});
	});
	

	// -----------------------------------------------------------------------------------
	// SETUP VIEW single PHOTO LINK
	// -----------------------------------------------------------------------------------
	jQuery('a.show_photo').bind('click', function(e) {
		e.preventDefault();

		if(this.rel == '') {
			return;
		};

		loadColorBox(http_host+'popup-show-photo.html?ilid='+this.rel);
	});

	// -----------------------------------------------------------------------------------
	// SETUP VIEW PHOTO LINK
	// -----------------------------------------------------------------------------------
	jQuery('a.view_vehicle_photo').bind('click', function(e) {
		e.preventDefault();
		
		if(this.rel == '') {
			return;
		};
		
		loadColorBox(http_host+'popup-view-photo.html?ilid='+this.rel);
	});

	// -----------------------------------------------------------------------------------
	// SETUP VIEW VIDEO LINK
	// -----------------------------------------------------------------------------------
	jQuery('a.view_vehicle_video').bind('click', function(e) {
		e.preventDefault();
		
		if(this.rel == '') {
			return;
		};
		
		loadColorBox(http_host+'popup-view-video.html?vlid='+this.rel);
	});

	// -----------------------------------------------------------------------------------
	// SETUP REPORT ABUSE LINK
	// -----------------------------------------------------------------------------------
	jQuery('a.button.report_abuse').live('click', function(e) {
		e.preventDefault();

		if(this.rel == '') {
			return;
		};

		loadColorBox(http_host+'popup-report.html?i='+this.rel);
	});

	// -----------------------------------------------------------------------------------
	// SETUP VIEW FRIENDS LINK
	// -----------------------------------------------------------------------------------
	jQuery('a.view_friends, a.button_friends').live('click', function(e) {
		e.preventDefault();

		if(this.rel == '') { 
			return;
		};

		loadColorBox(http_host+'popup-view-friends.html?member_id='+this.rel);
	});

	// -----------------------------------------------------------------------------------
	// SETUP VIEW FRIENDS LINK
	// -----------------------------------------------------------------------------------
	jQuery('a.button.post_a_comment, a.button.post_cc_comment').live('click', function(e) {
		e.preventDefault();
		
		if(this.rel == '') {
			return;
		};

		loadColorBox(http_host+'popup-showroom-submit-comment.html?i='+this.rel,700);
	});	
	
	// -----------------------------------------------------------------------------------
	// EXPAND SEARCH LINK
	// -----------------------------------------------------------------------------------
	jQuery('#expand_car_combat_search').live('click', function(e) {
		e.preventDefault();
		
		jQuery(this).closest('form').children('.box').toggle('blind',function(){
			fieldsetRatingSlider(".search_slider");
		});
	}).closest('form').children('.box').toggle('blind',0);
	
	
	// -----------------------------------------------------------------------------------
	// BILLING -- TOKENS
	// -----------------------------------------------------------------------------------
	jQuery("#token_quantity_box").change(function(){
		if(jQuery(this).val()!=""){
			jQuery("input[name=token_quantity]:checked")[0].checked=false;
		}
	});
	jQuery("input[name=token_quantity]").click(function(){
		jQuery("#token_quantity_box").val("");
	});
	
	if(jQuery("#tokens_remaining_box").length){
		jQuery("#tokens_remaining_box").height(jQuery("#purchase_tokens_box").height()-30);
	};

	// -----------------------------------------------------------------------------------
	// FREQUENTLY ASKED QUESTIONS
	// -----------------------------------------------------------------------------------
	jQuery("ul.faq li a.title").click(function(){
		jQuery(this).parent().toggleClass("show");
		return false;
	});

	// -----------------------------------------------------------------------------------
	// INITIALIZE -- COMMENT DELETORS
	//------------------------------------------------------------------------------------
	jQuery("#comments .list_item_delete, #image_comments .list_item_delete, #video_comments .list_item_delete, #vehicle_comments .list_item_delete, #blog_comments .list_item_delete").live('click', doDeleteComment);	

// -----------------------------------------------------------------------------------
}); // END DOCUMENT READY
//------------------------------------------------------------------------------------

// -----------------------------------------------------------------------------------
// INITIALIZE -- DISCLAIMER DIALOG
//------------------------------------------------------------------------------------

function showDisclaimer() {
	var dialog=$("#disclaimer").fadeIn("fast").children().first();
	dialog.css({left:($(window).width()-dialog.outerWidth())/2, top:($(window).height()-dialog.outerHeight())/2});
};

jQuery('input[name="disclaimer_cc_enable"]').live('click', function() {
	jQuery.getJSON(http_host+'modules/content/ajax/disclaimer-update.php', { cc_enabled : jQuery(this).val() });
});

jQuery('input[name="disclaimer_not_again"]').live('click', function() {
	jQuery.getJSON(http_host+'modules/content/ajax/disclaimer-update.php', { not_again : jQuery(this).is(':checked') });
});

// -----------------------------------------------------------------------------------
function toggleMore(){ // START -- TOGGLE MORE FEATURES ROWS
// -----------------------------------------------------------------------------------
	jQuery("tr.compare_more").toggle('blind',{},1000);
// -----------------------------------------------------------------------------------
} // END -- TOGGLE MORE
//------------------------------------------------------------------------------------

// -----------------------------------------------------------------------------------
function setOpacity(){ // START -- SET OPACITY
//------------------------------------------------------------------------------------
	jQuery(".uploadfields").css({"opacity":1});
	jQuery("div.disabled").css({"opacity":"0.25"});
// -----------------------------------------------------------------------------------
}; // END -- SET OPACITY
//------------------------------------------------------------------------------------
	
	
// -----------------------------------------------------------------------------------
function buttonHover(object){ // START -- BUTTON HOVER
//------------------------------------------------------------------------------------
	jQuery(object).each(function () {
	
		if(jQuery(this).closest(".container").length==0){
		
			// set up vars for originat styles to overwrite :hover
			var buttonURL = jQuery(this).css("background-image").replace(/"/g, '').replace(/url\(|\)$/ig, '');
			var buttonRepeat = jQuery(this).css("backgroundRepeat");
			var buttonPosition = jQuery(this).css("backgroundPosition");
			var buttonWidth = jQuery(this).width();
			var buttonHeight = jQuery(this).height();
			var buttonNewX = jQuery(this).width();
		
			// create the wraper span to apply effects to
			if(jQuery(this).find("span").length==0){
				jQuery(this)
				.css({'backgroundPosition': jQuery(this).css("backgroundPosition")})
				.wrapInner('<span />')
				.find("span")
				.css({
					'display':'block',
					'position':'absolute',
					'top':'0',
					'left':'0',
					'width':buttonWidth,
					'height':buttonHeight,
					'padding':'0',
					'background' : 'url('+buttonURL+') '+buttonRepeat+' -'+buttonNewX+'px 55%',
					'opacity':0
				});
			};
		
			if(jQuery(this).hasClass("disabled")) {
	
			} else {
	
				jQuery(this).bind("mouseover", function() {
					jQuery(this).find("span").stop().stop().fadeTo("fast",1);
				})
				.bind("mouseout", function() {
					jQuery(this).find("span").fadeTo("slow",0);
					return false;
				});
			
			};
		};
	
	});
	
	
// -----------------------------------------------------------------------------------
}; // END -- BUTTON HOVER
//------------------------------------------------------------------------------------


// -----------------------------------------------------------------------------------
function inputFocus() { // START -- INPUT FOCUS
//------------------------------------------------------------------------------------
	sfFocus = function() {
		var sfEls = document.getElementsByTagName("INPUT, TEXTAREA");
		for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onfocus=function() {
				this.className+=" focus";
				this.select();
			};
			sfEls[i].onblur=function() {
				this.className=this.className.replace(new RegExp(" focus\\b"), "");
			};
		};
	};
	if (window.attachEvent) window.attachEvent("onload", sfFocus);
	jQuery("input[type=text]").focus(function(){
	    this.select();
	});
// -----------------------------------------------------------------------------------
}; // END -- INPUT FOCUS
//------------------------------------------------------------------------------------


// -----------------------------------------------------------------------------------
function inputBlur(object, value) { // START -- INPUT BLUR
//------------------------------------------------------------------------------------
	jQuery(object).attr('value', value);
	jQuery(object).blur(function(){
		if(jQuery(this).val() == ''){
			jQuery(this).val(value);
		};
	}).focus(function(){
		if(jQuery(this).val() == value){
			jQuery(this).val('');
		};
	});
// -----------------------------------------------------------------------------------
}; // END -- INPUT BLUR
//------------------------------------------------------------------------------------


// -----------------------------------------------------------------------------------
function rotateNeedleWithSlider(object){ // START -- ROTATE NEEDLE WITH SLIDER
//------------------------------------------------------------------------------------
	jQuery(object).each(function(){
		// Hide Input
		jQuery(this).find('.amount').css({"visibility":"hidden"});
		// Find gauge
		jQuery(this).find(".gauge").each(function(){
			// Parse Current Number
			var originalValue = 0;
			var roundedValue = 0;
			if(jQuery(this).find('.current_rating').html().indexOf("%")==-1){
				originalValue = Math.round(parseFloat(jQuery(this).find('.current_rating').children('strong').html()) * 10);
				// Change Gauge displayed value
				jQuery(this).parents(object).find(".current_rating strong").text((originalValue / 10));
			} else {
				originalValue = Math.round(parseFloat(jQuery(this).find('.current_rating').children('strong').html()));
				// Change Gauge displayed value
				jQuery(this).parents(object).find(".current_rating strong").text(originalValue);
			}
			// Start Needle At Current Number (formulated to fit gauge)
			jQuery(this).find('.needle').rotate({angle:((originalValue*0.9) + 14) / 100 * 270});
			// Apply Slider
			jQuery(this).parents(object).find('.slider').slider({
				animate: "slow", // Animate Slow on Click
				value: originalValue, // Set default placement no Current Number
				slide: function(event, ui) {
			
					if(jQuery(this).parents(object).find('.current_rating').html().indexOf("%")==-1){
						// Change Input Value
						jQuery(this).parents(object).find('.amount').val((ui.value/10));
						// Change Guage displayed value
						jQuery(this).parents(object).find(".current_rating strong").text((ui.value/10));
					} else {
						// Change Input Value
						jQuery(this).parents(object).find('.amount').val((ui.value));
						// Change Guage displayed value
						jQuery(this).parents(object).find(".current_rating strong").text((ui.value));
					}
					// Rotate Needle When Dragging
					jQuery(this).parents(object).find('.needle').rotate({animateTo: (((ui.value) * 0.9) + 14) / 100 * 270} );
					
				}
			});
			// Apply Voter
			/*
			jQuery(this).parents(object).find('.voter').slider({
				animate: "slow",
				min: 1,
				value: 50,
				step: 1,
				slide: function(event, ui) {
					if(ui.value > 60){
						jQuery(this).parents(object).find('.amount').val(1);
						//jQuery(this).parents(object).find(".left .current_rating strong").text(100 - ui.value);
						//jQuery(this).parents(object).find(".right .current_rating strong").text(ui.value);
						//jQuery(this).parents(object).find('.needle_left').rotateAnimation((((100 - ui.value)*0.9)+14)/100*270);
						//jQuery(this).parents(object).find('.needle_right').rotateAnimation(((ui.value*0.9)+14)/100*270);
						jQuery(this).parents(object).find('.fire_left').stop().fadeTo("slow", 0);
						jQuery(this).parents(object).find('.fire_right').stop().fadeTo("slow", 1);
					};
					if(ui.value <= 60 && ui.value >= 40){
						jQuery(this).parents(object).find('.amount').val(0);
						//jQuery(this).parents(object).find(".current_rating strong").text(ui.value);
						//jQuery(this).parents(object).find('.needle').rotateAnimation(((ui.value*0.9)+14)/100*270);
						jQuery(this).parents(object).find('.fire_left, .fire_right').stop().fadeTo("slow", 0);
					}
					if(ui.value < 40){
						jQuery(this).parents(object).find('.amount').val(2);
						jQuery(this).parents(object).find('.fire_left').stop().fadeTo("slow", 1);
						jQuery(this).parents(object).find('.fire_right').stop().fadeTo("slow", 0);
						//jQuery(this).parents(object).find(".left .current_rating strong").text(Math.abs(100-ui.value));
						//jQuery(this).parents(object).find(".right .current_rating strong").text(Math.abs(ui.value));
						//jQuery(this).parents(object).find('.needle_left').rotateAnimation(((Math.abs(100-ui.value)*0.9)+14)/100*270);
						//jQuery(this).parents(object).find('.needle_right').rotateAnimation(((Math.abs(ui.value)*0.9)+14)/100*270);
					};
				}
			});
			*/
			
			
				
		});
	});	
// -----------------------------------------------------------------------------------
}; // END -- ROTATE NEEDLE WITH SLIDER
//------------------------------------------------------------------------------------


// -----------------------------------------------------------------------------------
function fieldsetRatingSlider(selector){ // START -- FIELDSET RATING SLIDER
//------------------------------------------------------------------------------------
	jQuery(selector).each(function(){
		jQuery(this).find(".hidden").css({"display":"inline"});
		jQuery(this).find("div.road_royalty_rating_range").css({"display":"none"});
		jQuery(this).find(".search_slider_toggle").slider({
			range: true,
			min: 0,
			max: 100,
			values: [25, 75],
			animate: "slow",
			slide: function(event, ui) {
				jQuery(this).parents(selector).find(".rating_range_low").val(ui.values[0]);
				jQuery(this).parents(selector).find(".rating_low").html(ui.values[0]);
				jQuery(this).parents(selector).find(".rating_range_high").val(ui.values[1]);
				jQuery(this).parents(selector).find(".rating_high").html(ui.values[1]);				
			}
		});

		var low_el	= jQuery(this).find('input[name="rating_range_low"]');
		var high_el	= jQuery(this).find('input[name="rating_range_high"]');

		var rating_low	= low_el.attr('value') == 0 ? 0 : low_el.attr('value');
		var rating_high	= high_el.attr('value') == 0 ? 100 : high_el.attr('value');

		low_el.attr('value', rating_low);
		high_el.attr('value', rating_high);

		jQuery(this).find('.rating_low').html(rating_low);
		jQuery(this).find('.rating_high').html(rating_high);
	});	
// -----------------------------------------------------------------------------------
}; // END -- FIELDSET RATING SLIDER
//------------------------------------------------------------------------------------


// -----------------------------------------------------------------------------------
function countdown(){ // START -- COUNTDOWN
//------------------------------------------------------------------------------------
	var has_one = false;

	 jQuery('.timer .time').each(function(){
		if(jQuery(this).html() != '00:00:00:00') {
			has_one = true;

			var vals = jQuery(this).html().split(':');
	
			/* Decriment seconds */
			vals[3]--;
	
			/* Seconds */
			if(vals[3] == -1) {
				vals[2]--;
				vals[3] = 59;
			};
	
			/* Minutes */
			if(vals[2] == -1) {
				vals[1]--;
				vals[2] = 59;
			};
	
			/* Hours */
			if(vals[1] == -1) {
				vals[0]--;
				vals[1] = 24;
			};
	
			if(vals[3] == 0) {
			//	return;
			}
	
			/* Zero pad time pieces */
			vals[0] = zeroPad(vals[0], 2);
			vals[1] = zeroPad(vals[1], 2);
			vals[2] = zeroPad(vals[2], 2);
			vals[3] = zeroPad(vals[3], 2);
			vals    = vals.join(':');
	
			jQuery(this).html(vals);
		};
	});

	if(!has_one) {
		clearInterval(countdown_interval);
	};
// -----------------------------------------------------------------------------------
}; // END -- COUNTDOWN
//------------------------------------------------------------------------------------


// -----------------------------------------------------------------------------------
function contentScrollWraper(object){ // START -- CONTENT SCROLL WRAPPER
//------------------------------------------------------------------------------------
	jQuery(object)
	.css({"overflow":"hidden", "padding":"0"})
	.wrapInner('<div class="scroll_container"></div>');
	
	return false;
// -----------------------------------------------------------------------------------
}; // END -- CONTENT SCROLL WRAPPER
//------------------------------------------------------------------------------------


// -----------------------------------------------------------------------------------
function mediaUploadBrowse(){
//------------------------------------------------------------------------------------
	jQuery('.module .box .content fieldset label.cabinet').mousemove(function(e){
	
		var position = $(this).position();
		var offset = $(this).offset();
		var x = e.pageX - (offset.left);
		var y = e.pageY - (offset.top);
		
		var inputWidth = jQuery(this).find('.file').width();
		var inputHeight = jQuery(this).find('.file').height();
		
		var xOffset = inputWidth - 20;
		var yOffset = inputHeight / 2;
		
		jQuery(this).find('.file').css({'display':'block','opacity':'0','cursor':'pointer','left': x - xOffset, 'top': y - yOffset});
		
	});
// -----------------------------------------------------------------------------------
};
//------------------------------------------------------------------------------------

function zeroPad(num, count){
	var num_zeropad = num + '';

	while(num_zeropad.length < count) {
		num_zeropad = '0' + num_zeropad;
	};

	return num_zeropad;
};

function enterHover(){
	if(jQuery(this).parent().hasClass('navigation')){
		jQuery(this).addClass("hover");
	};

	if(jQuery(this).parent().parent().hasClass('navigation')){
		jQuery(this).addClass('hover');
	};
};

function exitHover(){
	if(jQuery(this).parent().hasClass('navigation')){
		jQuery(this).removeClass('hover');
	};

	if(jQuery(this).parent().parent().hasClass('navigation')){
		jQuery(this).removeClass('hover');
	};
};

/* Primary Color Selector */
function colorClick(){
	var colors_ul = jQuery(this).parent();

	colors_ul.children().removeClass('active');
	jQuery(this).addClass('active');

	var c_name = jQuery(this).html();
	var c_code = c_name.toLowerCase() == 'black' ? '#fff' : jQuery(this).css('background-color');

	colors_ul.siblings('.primary_color_name').html(c_name).css('color', c_code);
	colors_ul.siblings('.primary_color_clear').css('display', 'block');
	colors_ul.siblings('input[name="primary_color"]').attr('value', c_name);

	return false;
};

/* Primary color clear */
function colorClear(){
	jQuery(this).siblings('ul.primary_color').children('.active').removeClass('active');
	jQuery(this).css('display', 'none');
	jQuery(this).siblings('.primary_color_name').html('All Colors').css('color', 'inherit');
	jQuery(this).siblings('input[name="primary_color"]').attr('value', '');

	return false;
};

/* Advanced Search - Button In Navigation for Big Drop Down */
function toggleAdvSearch(){
	var el = jQuery('#module_search');

	if(parseInt(el.css('top')) == -14) {
		jQuery(".navigation-search").fadeIn("fast");
		el.stop().animate({ 'top': '-900px' }, 600);
		return false;
	};
	
	jQuery(".navigation-search").fadeOut("fast");
	el.stop().animate({ 'top' : '-14px' }, 600);
	return false;
};

/* Blog details vote on poll */
jQuery('fieldset.poll a.button.vote').live('click', function(e) {
	e.preventDefault();

	if(this.rel == '') {
		return;
	}

	var option_id = jQuery('fieldset.poll input[name="poll_'+this.rel+'"]:checked').attr('value');

	if(option_id == undefined || option_id == '') {
		setStatus('Select a poll option.', 'false', 'fieldset.poll');
		return;
	};

	jQuery.getJSON(http_host+'modules/poll/ajax/vote.php', { poll_id : this.rel, option_id : option_id }, function(data, status) {
		if(status != 'success') {
			setStatus('Internal error - Please try again', 'fail', 'fieldset.poll');
			return;
		};

		setStatus(data.message, data.status, 'fieldset.poll');

		if(data.extra != '') {
			var pr = '<div class="column">';
			pr += '<p>'+data.extra.title+'</p>';
			pr += '<ul class="results">';

			for(i=0; i < data.extra.options.length; i++) {
				var vote_percent = data.extra.options[i].votes == 0 ? '0' : Math.round((data.extra.options[i].votes/data.extra.total_votes) * 100);
				
				pr += '<li>';
				pr += '<span class="title">'+data.extra.options[i].option+'</span>';
				pr += '<div class="bar"><div class="value" style="width: '+vote_percent+'%;">'+data.extra.options[i]['votes']+'</div></div>';
				pr += '</li>';
			};

			pr += '</ul>';
			pr += '</div>';

			jQuery('fieldset.poll').replaceWith(pr);
		};
	});
});

/* Code for confirm delete comment, remove in future if not used forever */
function askDeleteComment(){
	var el = jQuery(this);

	if(el.html() != 'Delete Comment'){
		return false;
	};

	el.html('Are you sure?');

	el.mouseout(function(){
		jQuery(this).stop().animate({width:"0px"},delete_comment_control_interval,function(){
			jQuery(this).html("Delete Comment").unbind("click").click(askDeleteComment);
		});
	});

	el.stop().animate({ width : '90px' }, delete_comment_control_interval, function(){
		jQuery(this).unbind('click').click(doDeleteComment);
	});

	return false;
};

/*
doColorBox(setScroll): reset the loaded colorbox's scrollbars, file uploaders, voters, colorbox links...
setScroll values:
	-1: scroll to bottom
	0: scroll to top
	100: scroll 100px down
*/

// -----------------------------------------------------------------------------------
function starRating(selector, star_width){ // STAR RATING
// -----------------------------------------------------------------------------------
jQuery(selector).each(function(){
	var orgHTML = jQuery(this).find(".reviews_count").find("em").html();
	var orgCount = parseFloat(jQuery(this).find(".reviews_count").find("strong").html());
	var p = jQuery(this).find(".stars").attr('id').replace(/vote_/, '').split('_');
	jQuery(this).find(".no_vote_yet").stars({
		inputType: "select",
		starWidth: star_width,
		split: 2,
		oneVoteOnly: true,
		callback: function(ui, type, value) {		
			jQuery.getJSON(http_host+'modules/content/ajax/rate-media.php?type='+p[0]+'&mvi='+p[1]+'&li='+p[2]+'&rating='+value, {rate: value}, function(data) {
				//if(data.status == 'pass') {
				//	jQuery('#vote_'+p.join('_')).siblings('ul li strong').replaceWith(data.extra);
				//	jQuery('#vote_'+p.join('_')).replaceWith('<div class="vote-status">'+data.message+'</div>');
				//} else {
				//	alert('Error: '+data.message);
				//};
			});
		}
	});
	jQuery(this).find(".did_vote")
	.css({"opacity":0.5})
	.stars({
		inputType: "select",
		starWidth: star_width,
		split: 2,
		disabled: true
	});
	jQuery(this).find("input[type=submit]").css({"display":"none"});
});
// -----------------------------------------------------------------------------------
}; // END STAR RATING
// -----------------------------------------------------------------------------------


// -----------------------------------------------------------------------------------
function doColorBox(setScroll){ // START -- COLORBOX (LIVE)
//------------------------------------------------------------------------------------

	// -----------------------------------------------------------------------------------
	// LAST CHILD : ADD FIRST / LAST CLASSES
	//------------------------------------------------------------------------------------
	jQuery("li:last-child").addClass("last");
    jQuery("li:first-child").addClass("first");

	// -----------------------------------------------------------------------------------
	// INITIALIZE -- ROTATE NEEDLE WITH SLIDER
	//------------------------------------------------------------------------------------
	rotateNeedleWithSlider('div.rating');
	
	// -----------------------------------------------------------------------------------
	// INITIALIZE -- EQUAL HEIGHT FOR CONTENT ITEMS WITH SAME REL
	//------------------------------------------------------------------------------------
	equalHeight(jQuery('.content.combat_details'));
	equalHeight(jQuery('.content.combat_statistics'));
	equalHeight(jQuery('.content.vehicle_profile_media'));
	
	// -----------------------------------------------------------------------------------
	// INITIALIZE -- INPUT FOCUS
	//------------------------------------------------------------------------------------
	inputFocus();
	
	// -----------------------------------------------------------------------------------
	// INITIALIZE -- BUTTON HOVER ("A" ONLY)
	//------------------------------------------------------------------------------------
	buttonHover(".module a.button");
	
	// -----------------------------------------------------------------------------------
	// INITIALIZE -- STAR RATING
	// -----------------------------------------------------------------------------------
	starRating(".star_rating.large", 28);
	starRating(".star_rating.small", 16);
	
	// -----------------------------------------------------------------------------------
	// REINITIALIZE -- CONTENT SCROLL WRAPPER
	//------------------------------------------------------------------------------------
	//contentScrollWraper("#colorbox .content.scroll");
	
	// -----------------------------------------------------------------------------------
	// REINITIALIZE -- SET OPACITY
	//------------------------------------------------------------------------------------
	setOpacity();

	/*
	// -----------------------------------------------------------------------------------
	// REINITIALIZE -- SCROLL BOXES
	//------------------------------------------------------------------------------------
	var scroll_boxes = jQuery("div.scroll_container");
	if(scroll_boxes.length){
		scroll_boxes.scrollbar();
		if(setScroll){
			scroll_boxes.each(function(){
				this.scrollTo(setScroll);
			});
		};
	};
	*/
	
	// -----------------------------------------------------------------------------------
	// INITIALIZE -- MEDIA UPLOAD BROWSE
	//------------------------------------------------------------------------------------
	mediaUploadBrowse()
	
	// -----------------------------------------------------------------------------------
	// INITIALIZE -- FIELDSET RATING SLIDER
	//------------------------------------------------------------------------------------
	fieldsetRatingSlider(".search_slider");


	// -----------------------------------------------------------------------------------
	// REINITIALIZE -- COLORBOX LINKS
	//------------------------------------------------------------------------------------
	var colorboxers=jQuery(".colorbox");
	if(colorboxers.length){
		colorboxers.click(function(e){
			e.preventDefault();
			loadColorBox(jQuery(this).attr("href"));
		});
	};
	

	// -----------------------------------------------------------------------------------
	// REINITIALIZE -- FILE UPLOADER BUTTONS
	//------------------------------------------------------------------------------------
	jQuery('#upload_button').each(function() {
		var mvi		= jQuery('#upload_tos').attr('value');
		var type	= jQuery(this).attr('rel');
		var tos		= jQuery('#upload_tos').attr('checked') === true;

		showroomUploadMediaNew(jQuery(this), mvi, type, '#upload_tos');
	});
	
	
	
// -----------------------------------------------------------------------------------
}; // END -- COLORBOX (LIVE)
//------------------------------------------------------------------------------------

// -----------------------------------------------------------------------------------
function equalHeight(group) { // START -- EQUAL HEIGHT
//------------------------------------------------------------------------------------
    var tallest = 0;
    group.each(function() {
        var thisHeight = $(this).height();
        if(thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    jQuery(group).attr('style', 'height: '+tallest+'px !important');

// -----------------------------------------------------------------------------------
}; // END -- EQUAL HEIGHT
//------------------------------------------------------------------------------------

// -----------------------------------------------------------------------------------
//	DELETE COMMENT (LIVE)
//------------------------------------------------------------------------------------
function doDeleteComment(){
	// Clear out any existing status
	setStatus(false);

	var ci	= jQuery(this).attr('rel').split('|');
	var t	= ci.length == 2 ? ci[1] : '';
	var ci	= ci[0]

   jQuery(this).parent().slideUp(delete_comment_slide_interval,function(){
		// If there are no more comments left, show the message that there are no comments
		if(jQuery(this).siblings().length == 1) {
			jQuery(this).siblings().slideDown(delete_comment_slide_interval);
		};

		// Remove comment
		jQuery(this).remove();

		// Update counts
		if(parseInt(jQuery('#'+t+'_comments_total').html())-1 <= 0) {
			jQuery('#'+t+'_comments_showing, #'+t+'_comments_total').html('0');
			jQuery('#'+t+'_comments li.no_comments').show();
		} else {
			jQuery('#'+t+'_comments_showing').html(parseInt(jQuery('#'+t+'_comments_showing').html())-1);
			jQuery('#'+t+'_comments_total').html(parseInt(jQuery('#'+t+'_comments_total').html())-1);
		}

		jQuery.getJSON(http_host+'modules/content/ajax/delete-comment.php?ci='+ci, function(data) {			
			/*
			// Reinitialize scroll boxes
			var scroll_boxes = jQuery("div.scroll_container");
			if(scroll_boxes.length){
				scroll_boxes.scrollbar();
			};
			*/
			
		});
	});

   return false;
};

function hideLoading(){
	jQuery('.loading').removeClass('show');
	
	/*
	// reinitialize scroll boxes
	jQuery("div.scroll_container").scrollbar().each(function(){
		this.scrollTo(0);
	});
	*/
	
	doColorBox();
};

// -----------------------------------------------------------------------------------
//	COLORBOX (LOAD)
//------------------------------------------------------------------------------------
function loadColorBox(mylink,width){
	var params={ href : mylink, open : true };
	if(width!==undefined) params.width=width;
	jQuery.fn.colorbox(params, doColorBox);
};

function loadVehicleManufacturers(form_el) {
	jQuery(form_el).find('select[name="manufacturer"]').html('<option value="">Loading...</option>');

	jQuery.getJSON(http_host+'modules/content/ajax/get-vehicle-options.php', { v_type: jQuery(form_el).find('select[name="vehicle_type"]').attr('value'), type: 'manufacturer' }, function(data, status) {
		if(data.status == 'fail' || data.extra == '') {
			/* Block is required to fix IE8 problem with repopulating a select */
			jQuery(form_el).find('select[name="manufacturer"]').html('<option value="">'+data.message+'</option>').css({display:'block'});
		} else {
			/* Block is required to fix IE8 problem with repopulating a select */
			jQuery(form_el).find('select[name="manufacturer"]').html(data.extra).css({display:'block'});
		};
	});

	return true;
}

function loadVehicleModels(form_el) {
	jQuery(form_el).find('select[name="model"]').html('<option value="">Loading...</option>');

	jQuery.getJSON(http_host+'modules/content/ajax/get-vehicle-options.php', { v_type: jQuery(form_el).find('select[name="vehicle_type"]').attr('value'), type: 'model', id: jQuery(form_el).find('select[name="manufacturer"]').attr('value') }, function(data, status) {
		if(data.status == 'fail' || data.extra == '') {
			jQuery(form_el).find('select[name="model"]').html('<option value="">'+data.message+'</option>');
		} else {
			jQuery(form_el).find('select[name="model"]').html(data.extra);
		};
	});

	return true;
};

function pauseComp(ms) {
	var date	= new Date();
	var curDate	= null;

	while(curDate-date < ms) {
		curDate = new Date(); 
	};
};

/* setStatus function to set the status message on popup colorboxes
the status parameter is the text of the status message or pass false to remove the status message
the passclass parameter is 'pass'|'fail' depending on which class to apply to the div. 
setStatus(false); - remove the message
setStatus("File Upload Successful","pass"); - set the message */
function setStatus(status,passclass,selector){
	selector = selector == undefined ? 'fieldset' : selector;
	try{
		var fieldset 	= jQuery("#cboxLoadedContent").find(selector);
		var cstat	 	= fieldset.find("div.form-status");
		var status_note = '';

		if(status !== false) {
			if(status.indexOf('|') > -1) {
				status = status.split('|');
				status_note = status[1];
				status = status[0];
			};

			if(status_note == '') {
				switch(passclass) {
					case 'fail' :
						status_note = 'Please properly complete all required fields.';
					break;
					case 'pass' : 
						status_note = 'Success';
					break;
					case 'form_error' : 
						status_note = 'Form Error';
					break;
				};
			};
		};

		if(cstat.length) {
			if(status === false){
				cstat.remove();
			} else {
				cstat.removeClass("fail").removeClass("pass").addClass(passclass).html("<h6>"+status+"</h6><p>"+status_note+"</p>");
			};
		} else if(status !== false) {
			fieldset.prepend("<div class=\"form-status "+ passclass +"\"><h6>"+status+"</h6><p>"+status_note+"</p></div");			
		};
		
		if(fieldset.parent().hasClass("scroll")==false){
			jQuery.fn.colorbox.resize();
		}
		jQuery("#cboxLoadedContent").find(".content.scroll").scrollTop(0);
		/*
		//reinitialize scroll boxes
		var scroll_boxes = jQuery("div.scroll_container");
		if(scroll_boxes.length){
			scroll_boxes.scrollbar();
		};
		*/
		
	} catch(err){};
};

/* setUploadFilename function is triggered by upload file selection to 
populate the file name and to add more fields as needed */
function setUploadFilename() {
	jQuery(".uploadfields").css({"opacity":1});
	jQuery("input.file").css({"opacity":0});
	jQuery('#'+jQuery(this).attr('name')+'_filename').attr('value', this.value);
	
	// -----------------------------------------------------------------------------------
	// INITIALIZE -- MEDIA UPLOAD BROWSE
	//------------------------------------------------------------------------------------
	mediaUploadBrowse();
	var add_more = true;

	if(max_uploads != undefined && max_uploads != null && max_uploads <= jQuery('.uploadfields .upload').length) {
		add_more = false;
	} else {
		jQuery('.uploadfields .upload').each(function(n, el) {
			if(jQuery(el).attr('value') == '') {
				add_more = false;
				return;
			};
		});		
	};

	if(add_more) {
		var l = parseInt(jQuery('.upload:last').attr('rel'));

		for(var i=(l+1); i<=l+1; ++i) {
			jQuery('.uploadfields .section:last').after('<div class="section" style="display:block;"><input type="text" id="file'+i+'_filename" class="input medium upload" rel="'+i+'"><label class="cabinet"><input type="file" id="file'+i+'" name="file'+i+'" class="file"></label></div>');
			jQuery('#file'+i)[0].onchange = setUploadFilename;			
		};
		/*
		jQuery('.uploadfields .section:gt('+((l-1))+')').slideDown('slow', function() {
			doColorBox(-1);
		});
		*/
		doColorBox(-1);
	};
};

function showLoading(){
	jQuery('.loading').addClass('show');
};

function submitComment(type, type_id, populate) {
	showLoading();

	if(type == undefined || type_id == undefined) {
		setStatus('Invalid request', 'fail', 'fieldset.post_comment');
		hideLoading();
		return false;
	}

	var comment		= jQuery('textarea#message_comment').attr('value');
	var comments	= '#'+type+'_comments';
	var comments_cnt= '#'+type+'_comments_showing';
	var comments_ttl= '#'+type+'_comments_total';

	if(comment == '') {
		setStatus('Comment cannot be empty', 'fail', 'fieldset.post_comment');
		hideLoading();
		return false;
	};

	jQuery.post(http_host+'modules/content/ajax/post-comment.php', {type: type, type_id: type_id, comment: comment}, function(data) {
		if(data.status == 'pass') {
			// Clear out comment
			jQuery('#message_comment').attr('value', '');

			// Change cancel btn to close btn
			jQuery('a.cancel').removeClass('cancel').addClass('close').html('Close');
			
			if(populate !== false) {
				// Add new comment
				jQuery(comments+' li.no_comments').after('<li>'+data.extra+'<span class="clear"></span></li>').hide();
				
				// Update counts
				jQuery(comments_cnt).html(parseInt(jQuery(comments_cnt).html())+1);
				jQuery(comments_ttl).html(parseInt(jQuery(comments_ttl).html())+1);
			};

			setStatus(data.message, data.status, 'fieldset.post_comment');
		} else {
			setStatus(data.message, data.status, 'fieldset.post_comment');			
		};
		
		hideLoading();
		return true;
	}, 'json');
};

function sendMessage(member_id) {
	var sbj = jQuery('#message_subject').attr('value');
	var msg = jQuery('#message_message').attr('value');

	if(member_id == undefined) {
		setStatus('Invalid member selection.', 'fail');
		return false;
	};

	if(sbj == '') {
		jQuery('#message_subject').focus();
		setStatus('Subject is required.', 'fail');
		return false;
	};

	if(msg == '') {
		jQuery('#message_message').focus();
		setStatus('Message is required.', 'fail');
		return false;
	};

	// Hide form
	showLoading();
	var fo = jQuery('form[name="send_msg"]');
	jQuery('.form-status', fo).remove();

	jQuery.post(fo.attr('action'), {to:member_id, subject:jQuery('#message_subject').attr('value'), message:jQuery('#message_message').attr('value')}, function(d, s) {
		if(s != 'success') {
			setStatus('Failed to connect to server.', 'fail');
			hideLoading();
			return false;
		};
			
		if(d.status == 'pass') {
			jQuery('form[name="send_msg"] #message_subject').attr('value', '');
			jQuery('form[name="send_msg"] #message_message').attr('value', '');
			jQuery('a.cancel').removeClass('cancel').addClass('close').html('Close');
		};

		setStatus(d.message, d.status);
		hideLoading();
	}, 'json');

	return false;
};

function submitReport(content_id, content) {
	if(content_id == undefined || content == undefined) {
		setStatus('Invalid request.', 'fail');
		return false;
	};

	var priority	= jQuery('#report_priority option:selected').attr('value');
	var reason		= jQuery('#report_reason option:selected').attr('value');
	var comments	= jQuery('#report_comments').attr('value');

	if(priority == '' || reason == '') {
		setStatus('Priority and Reason are required.', 'fail');
		return false;
	};

	if(reason == 'other' && comments == '') {
		setStatus('If selecting other, please explain below.', 'fail');
		return false;
	};

	showLoading();

	jQuery.post(http_host+'modules/content/ajax/submit-report-abuse.php', { content_id: content_id, content: content, priority: priority, reason: reason, comments: comments }, function(d, s) {
		if(s != 'success') {
			setStatus('Failed to connect to server.', 'fail');
			hideLoading();
			return false();
		};

		if(d.status == 'pass') {
			jQuery('#report_priority option:eq(0)').attr('selected', true);
			jQuery('#report_reason option:eq(0)').attr('selected', true);
			jQuery('#report_comments').attr('value', '');
		};

		setStatus(d.message, d.status);
		hideLoading();
	}, 'json');
};

function build_push_to(url, https) {
	host	= https ? https_host : http_host;
	url		= url == undefined ? jQuery.url.attr('relative') : url;

	return jQuery.base64Encode(host+url);
}

