// perform JavaScript after the document is scriptable.
$(function() {
	
	$("#search-how-to").autocomplete('/how_to/auto_suggest',{ 
		width: 507,
		max: 10,     
		highlight: false, 		
		selectFirst: false,
		scroll: true,
		scrollHeight: 300
	});	
	
	
	// "Helpful / Not Really Helpful" on "How to page"
	$('.btn_helpful').click( function() { 
							var site_url	=	$('#site_url').val();
							var user_id		=	$("#userid");
							var content_type	=	$("#content_type");
							var remote_id	=	$("#remoteid");
							var rate_data	=	$(this).attr('rel');
							var bln_rate;
							var url			=	$(this).attr('href');	
							var sid			=	(Math.round((Math.random()*9)+1));
							var refresh_count;
							var feedback_text = $(this).parent();
							//var block_panel	=	$(this).parent();
							
							if (!user_id.val()) {
								$.ubox(site_url+'/user/login/');
								return;
							}
							
							rating_data = rate_data.split("|");
							bln_rate = rating_data[0];
							refresh_count = $("#"+rating_data[1]).text();
							
							var data		=	Array();
								   
							data.push( 'content_type=' + content_type.val() );
							data.push( 'remoteid=' + remote_id.val() );
							data.push( 'userid=' + user_id.val() );
							data.push( 'rating=' + bln_rate );
							
							var params = data.join('&');
							
							// do ajax call
							$.ajax({
											
									type		:	'post',
									url			:	'/ratings/rate?sid='+sid,
									data		:	params,
									dataType	:	'json',
									async		:	false,
									beforeSend	:	function() {
											//prompt_activity( block_panel, "Please wait..." );
											//block_panel.block({ message: "Please wait..." });
										},
									success		:	function( data ) {
											if (data.response == 'Success') {
												//prompt_activity( block_panel, "Rating sent..." );
												//$( block_panel ).unblock();
												//alert( "Your rate has been submitted!" );
												if (data.current_rating != bln_rate) {
													val_new_rate = (bln_rate == 1) ? parseInt(refresh_count) + 1 : refresh_count - 1
													$("#"+rating_data[1]).text(val_new_rate);
													feedback_text.html('<span style="float:left;color:#016D95;">Thanks for your vote!</span>');
												} else {
													feedback_text.html('<span style="float:left;color:#016D95;">Your vote was already saved!</span>');
												}
											} else {
												//prompt_activity( block_panel, data.response );
												//$( block_panel ).block({ message: data.response });
												alert( data.response );
											}
											
										}, 
									error		:	function() {
											alert( "An error occured.\nPlease try again later." );
										}							
									})
							return false; 
						});
	
	// "Helpful / Not Really Helpful" on "How to page"
	$('.btn_video_helpful').click( function() { 
							var site_url	=	$('#site_url').val();
							var user_id		=	$("#userid");
							var content_type	=	$("#video_content_type", $(this));
							var remote_id	=	$("#video_remoteid", $(this));
							var rate_data	=	$(this).attr('rel');
							var bln_rate;
							var url			=	$(this).attr('href');	
							var sid			=	(Math.round((Math.random()*9)+1));
							var refresh_count;
							var feedback_text = $(".helplink");
							//var block_panel	=	$(this).parent();
							
							if (!user_id.val()) {
								$.ubox(site_url+'/user/login/');
								return;
							}
							
							rating_data = rate_data.split("|");
							bln_rate = rating_data[0];
							refresh_count = $("#"+rating_data[1]).text();
							
							var data		=	Array();

							data.push( 'content_type='  + content_type.val() );
							data.push( 'remoteid=' + remote_id.val() );
							data.push( 'userid=' + user_id.val() );
							data.push( 'rating=' + bln_rate );
							
							var params = data.join('&');
							
							// do ajax call
							$.ajax({
											
									type		:	'post',
									url			:	'/ratings/rate?sid='+sid,
									data		:	params,
									dataType	:	'json',
									async		:	false,
									beforeSend	:	function() {
											//prompt_activity( block_panel, "Please wait..." );
											//block_panel.block({ message: "Please wait..." });
										},
									success		:	function( data ) {
											if (data.response == 'Success') {
												//prompt_activity( block_panel, "Rating sent..." );
												//$( block_panel ).unblock();
												//alert( "Your rate has been submitted!" );
												if (data.current_rating != bln_rate) {
													val_new_rate = (bln_rate == 1) ? parseInt(refresh_count) + 1 : refresh_count - 1
													$("#"+rating_data[1]).text(val_new_rate);
													feedback_text.html('<span style="float:left;color:#016D95;">Thanks for your vote!</span>');
												} else {
													feedback_text.html('<span style="float:left;color:#016D95;">Your vote was already saved!</span>');
												}
											} else {
												//prompt_activity( block_panel, data.response );
												//$( block_panel ).block({ message: data.response });
												alert( data.response );
											}
											
										}, 
									error		:	function() {
											alert( "An error occured.\nPlease try again later." );
										}							
									})
							return false; 
						});

	// Update community labor hour estimate on HOWTO article page
	/* this widget was removed 
	if($('.spin-button').length){
		$('.spin-button').SpinButton({min:0,max:100,round:2});
		$('.spin-button').keypress(function(e){
			var code = e.which;
			if(code==46 || code==8 || code==0){
				return true;
			}
			if(code<48 || code>57){
				return false;
			}
		})
		$('.btn-update').click(function(){
			var rating = $('.spin-button').val();
			var userid = $('#userid').val();
			var diyid = $('#diy_id').val();
			var content_type = 'labor_hour';
			var remoteid = diyid;
			var param = {'content_type':content_type, 'remoteid':remoteid, 'userid':userid,'rating':rating};
			$.post('/ratings/rate', param, function(data){
				var msg = eval('(' + data + ')');
				if(!msg.rating){
					alert(msg.response);
				} else {
					//alert(msg.response);
					$('.matt').html(Math.round(msg.rating*100)/100+' hours');
					$('#estimatebox').slideToggle();
				}
			});
		})
	}
	*/ 
	// allow video upload for logged users only
	$('.share-yours').click(function(){
		var site_url = $('#site_url').val();
		var url = $('#upload_url').val();
		var userid = $('#userid').val();
		
		if(!userid){
			$.ubox(site_url+'/user/login?url='+url);
			return;
		}
		location = url;
	});
	
	//Default Action
	$(".how-to-heroshot-display div").hide(); //Hide all content
	$("ul.tabs li:first").addClass("current").show(); //Activate first tab
	$(".how-to-heroshot-display div:first").show(); //Show first tab content
	
	//On Click Event
	$("ul.tabs li").click(function() {
		$("ul.tabs li").removeClass("current"); //Remove any "active" class
		$(this).addClass("current"); //Add "active" class to selected tab
		$(".how-to-heroshot-display div").hide(); //Hide all tab content
		var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
		$(activeTab).show(); //Fade in the active content
		return false;
	});
	
	// Uploading photo for instruction
	$('.submit_instruction_photo').click(function() {
		
		var userid = $("#userid").val();
		var url = $(this).attr('href');
		var site_url = $("#site_url").val();
		
		if (! userid) {
			$.ubox(site_url+'/user/login?ubox_url='+escape(url));
		} else {
			$.ubox(site_url+url);
		}
		
		return false;
		
	})
	
	// Improve this step for instruction
	$('.btn_improve_step').click(function() {
		var site_url = $("#site_url").val();
		var url = $(this).attr('href');
		if ($.ubox) {
			$.ubox(site_url+url);
		};
		return false;
	})
	
	// contributor names
	$('.more_names').hide();
	$('.show_more_names').click(function() {
		//$(this).parent(0).html('');
		$('.more_names').show();
		$(this).parent().hide();
	})
	
	$(".btn-continue").click(function(){ 
		if($('#how-to-year').val() == ''){
			alert("Please select year, make and model to continue.");
			return false;
		}
		if(($('#how-to-make').val() == '' ||  $('#how-to-make').val() == undefined)){
			alert("Please select make and model to continue.");
			return false;
		}
		if(($('#how-to-model').val() == '' ||  $('#how-to-model').val() == undefined)){
			alert("Please select model to continue...");
			return false; 
		} 
	})
	
	$("#howto-sidebar-find-shop").submit(function(){
		/** Set Analytics Data **/
		var scevar      = [];
	        scevar['eVar1'] = $('#find-shop-name').val();
	    var scevent     = ['event4']
	    sclinkCode(s_account, 'Find a Shop', scevent, scevar);
		/** Set Analytics Data **/
	}); 
	
	/* email this article button */
	$("a.btn_email_article").click(function() {
		// check first if ubox was loaded
		if($.ubox) {
			// fire ubox popup
			var pop_url = $(this).attr('rel');
			$.ubox(pop_url);
		}
		return false;
	})
	
	/* fix 4767 spinbutton */
	var all_wrapper = $("div#all");
	$("div#estimatebox").hover(
		function(){
			all_wrapper.css('position','static');
			},
		function(){
			all_wrapper.css('position','relative');
		})
		
	$("form#how_to_search_module").submit(function() {
		var this_text = $("input#search-how-to", this);
		if (this_text.val() == '' || this_text.val() == 'Enter keywords, or problem') {
			alert('Please enter a keyword/s to search');return false;
		}
	})
	
	/* UGC edits to how to guides */
	var validate_user = function(r) {
		if($('#userid').val()){
			return true;
		} else {
			var site_url = $('#site_url').val();
			$.ubox( site_url + '/user/login/'+r );
			return;
		}
	}
	
	$('.add_steps').click( function() {
		var r = $(this).attr('rel');
		//if(validate_user(r)) {
			$('.edit_button').slideUp();
			$('.step_div').slideUp();
			$('div.textarea').slideDown();
			$('.edit_all').slideDown();
		//}
	})
	
	$('.cancel_step', $('.edit_all')).click( function() {
		$('.step_div_preview').each(function(){
			$(this).html('');
		})
		
		$('.step_div').slideDown();
		$('div.textarea').slideUp();
		$('.edit_all').slideUp();
		
		$('.textarea').each(function(){
			var txt = $('#instruction_text_hid', this).val();
			$('#instruction_text', this).val(txt);
		})
		
	})
	
	$('.preview_step', $('.edit_all')).click( function() {
		$('.w .oh').each(function(){
			var par      = this;
			var txtarea  = $('.textarea', par);
			var stepview = $('.step_div_preview', par);
			
			var txt = $('#instruction_text', txtarea).val();
			$(stepview).html(txt);
		})
	})
	
	$('.save_step', $('.edit_all')).click( function() {
		
		var r = $('input:hidden#diy_url').val();
		var step_key = 'all';
		var use_step_key = $('input#steps_save');
		if(!validate_user(r)) { 
			use_step_key.val(step_key);
			return;
		}
		
		$('.w .oh').each(function(){
			var par      = this;
			var stepdiv  = $('.step_div', par);
			var txtarea  = $('.textarea', par);
			var stepview = $('.step_div_preview', par);
			
			var url    = $('#site_url').val();
			var vmapid = $('#vehicleid', txtarea).val();
			var insid  = $('#instructionid', txtarea).val();
			var relid  = $('#diy_rel_id', txtarea).val();
			var userid = $('#userid').val();
			var instxt = $('#instruction_text', txtarea).val();
			var instxt_old = $('#instruction_text_hid', txtarea).val();
			
			if(instxt!=instxt_old)
			{
				$.get(
					url + '/how_to/instruction_suggestion',
					{vehicleid:vmapid, instructionid:insid, diy_rel_id:relid, userid:userid, instruction_text:instxt},
					function(data){
						var data = eval('(' + data + ')');
						if(data.instruction_suggestionid)
						{
							var msg = 'Success! Thank you for making AutoMD better. Your contribution has been added to this article.';
							$(stepview).html('');
							$('.step_div .step_txt', par).html(instxt);
							$('#instruction_text_hid', txtarea).val(instxt);
							$(stepdiv).slideDown();
							$(txtarea).slideUp();
						}
					}
				);
			}
			else
			{
				$('.step_div').slideDown();
				$('div.textarea').slideUp();
				$('.edit_all').slideUp();
				
				$(stepview).html('');
			}
		})
	})
	
	$('.w .oh').each(function(){
		var par      = this;
		var stepdiv  = $('.step_div', par);
		var txtarea  = $('.textarea', par);
		var stepview = $('.step_div_preview', par);
		var edit_button = $('.edit_button', par);
		
		$('.edit_step', par).click( function() {
			var r = $(this).attr('rel');
			//if(validate_user(r)) {
				$(stepdiv).slideUp();
				$(txtarea).slideDown();
				$(edit_button).slideDown();
			//}
		})
		
		$('.cancel_step', par).click( function() {
			$(stepview).html('');
			$(txtarea).slideUp();
			$(edit_button).slideUp();
			$(stepdiv).slideDown();
			
			var txt = $('#instruction_text_hid', txtarea).val();
			$('#instruction_text', txtarea).val(txt);
		})
		
		$('.preview_step', par).click( function() {
			var txt = $('#instruction_text', txtarea).val();
			$(stepview).html(txt);
		})
		
		$('.save_step', par).click( function() {
			
			var r = $('input:hidden#diy_url').val();
			var step_key = $('input#step_key', par).val();
			var use_step_key = $('input#steps_save');
						
			if(!validate_user(r)) { 
				use_step_key.val(step_key);
				return;
			}
			
			var url    = $('#site_url').val();
			var vmapid = $('#vehicleid', txtarea).val();
			var insid  = $('#instructionid', txtarea).val();
			var relid  = $('#diy_rel_id', txtarea).val();
			var userid = $('#userid').val();
			var instxt = $('#instruction_text', txtarea).val();
			var instxt_old = $('#instruction_text_hid', txtarea).val();
			
			if(instxt!=instxt_old)
			{
				$.get(
					url + '/how_to/instruction_suggestion',
					{vehicleid:vmapid, instructionid:insid, diy_rel_id:relid, userid:userid, instruction_text:instxt},
					function(data){
						var data = eval('(' + data + ')');
						if(data.instruction_suggestionid)
						{
							alert('Success! Thank you for making AutoMD better. Your contribution has been added to this article.');
							$(stepview).html('');
							$('.step_div .step_txt', par).html(instxt);
							$('#instruction_text_hid', txtarea).val(instxt);
							$(stepdiv).slideDown();
							$(txtarea).slideUp();
							$(edit_button).slideUp();
						}
					}
				);
			}
		})
		
	})
	
	/* HOW-TO GUIDE DETAIL */
	var parent = $('.verified-tab-nav');
	
	$('li', parent).click(function(){
		
		var part = $(this).attr('class');
		
		if(part=='v-part')
		{
			$('.display-tab').hide();
			$('.watch-video-tab').show();
		}
		else
		{
			$('.display-tab').show();
			$('.watch-video-tab').hide();
		}
		$('a', parent).removeAttr('class');
		$('a', this).attr('class', 'current');
	})
	
	$('.right-tab-c').each(function(){
		var par = this;
		$('.fold', par).click(function(){
			var txt = $(this).html();
			var label = $(this).attr('rel');
			
			if(txt=='(Show)')
			{
				$('.tcount', par).hide();
				$('.matt', par).stop().show();
				$('.clear img', par).attr('src', '/images/arrow-down-ico.jpg');
				$(this).html('(collapse)');
			}
			else
			{
				$('.tcount', par).show();
				$('.matt', par).hide();
				$('.clear img', par).attr('src', '/images/arrow-right-ico.jpg');
				$(this).html('(Show)');
			}
		})
	})
	
	$('.btn-view-details').unbind("click").click(function(){
		var year_id = $('#year_id').val();
		var make_id = $('#make_id').val();
		var model_id = $('#model_id').val();
		var submodel_id = $('#submodel_id').val();
		var engine_id = $('#engine_id').val();
		var diy_id = $('#diy_id').val();
		var zip = $('#zip').val();
		var diagnosis_key = $('#diagnosis_key').val();
		var scPage = $('#scPage').val();
		var site_url = $('#site_url').val();
		//var redirect = $('#current_page').val();
		
		/*schandleOnclickEvent('s_account','/estimate_costs/detail?{if $vehicles}year={$vehicles[0].year.year_id}&make={$vehicles[0].make.make_id}&model={$vehicles[0].model.model_id}{if $vehicles[0].submodel.submodel_id}&submodel={$vehicles[0].submodel.submodel_id}{/if}{if $vehicles[0].engine.engine_id}&engine={$vehicles[0].engine.engine_id}{/if}{/if}&jobs[]={$diy_id}&zip={$location.zip}{if $diagnosis_key}&key={$diagnosis_key}{/if}','event6', 'eVar2', null, 'Cost Estimate', '{$scPage}');*/
		var url = '/estimate_costs/detail?year='+year_id+'&make='+make_id+'&model='+model_id+'&jobs[]='+diy_id+'&zip='+zip;
		
		if (submodel_id) {url = url + '&submodel='+submodel_id};
		if (engine_id) {url = url + '&engine='+engine_id};
		if (diagnosis_key) {url = url + '&key='+diagnosis_key};
		
		if(!year_id || !make_id || !model_id || !submodel_id || !engine_id )
		{
			$.ubox(site_url+'/how_to/vehicle_select/?diy_id='+diy_id+'&zip='+zip+'&method=get&action=/estimate_costs/detail/&t=1');
			return;
		} else {
			schandleOnclickEvent('s_account', url, 'event6', 'eVar2', null, 'Cost Estimate', scPage);
		}
	})
		
	$(".lb-how-to-btn-continue").click(function(){
		var engine = $(".engine").val();
		if(engine==''){
			alert('Please select year, make, model, submodel and engine to continue.');
			return;
		} else {
			$('#garage-carpicker').submit();
		}
	})

}) 
	
function init_howto_step_save( userid )
{
	step = $('#steps_save').val();
	trig_howto_save_step( step, userid );
}

function trig_howto_save_step( steps, userid )
{
	if (!steps) return;
	
	var step_panel = ( steps == 'all') ? $('div.textarea') : $('div#edit_step'+steps+'_panel');
	var vmapid = $('#vehicleid', step_panel).val();
	var insid  = $('#instructionid', step_panel).val();
	var relid  = $('#diy_rel_id', step_panel).val();
	var instxt = $('#instruction_text', step_panel).val();
	var instxt_old = $('#instruction_text_hid', step_panel).val();
	var data = '';
	
	
	if (steps == 'all')
	{
		step_panel.each(function() {
			
			vmapid = $('#vehicleid', this).val();
			insid  = $('#instructionid', this).val();
			relid  = $('#diy_rel_id', this).val();
			instxt = $('#instruction_text', this).val();
			instxt_old = $('#instruction_text_hid', this).val();
			data = 'vehicleid=' + vmapid + '&instructionid=' + insid + '&diy_rel_id=' + relid + '&userid=' + userid + '&instruction_text=' + instxt;
			save_howto_step_ajx(data);
			
		})
	}
	else
	{
		data = 'vehicleid=' + vmapid + '&instructionid=' + insid + '&diy_rel_id=' + relid + '&userid=' + userid + '&instruction_text=' + instxt;
		save_howto_step_ajx(data);
	}
	alert('Success! Thank you for making AutoMD better. Your contribution has been added to this article.');
}

function save_howto_step_ajx(p_data)
{
	var sid = Math.floor(Math.random()*11);
	var action_save_step = '/how_to/instruction_suggestion';
	
	$.ajax({
		url : action_save_step,
		data : p_data+'&sid='+sid,
		type : 'get',
		dataType:'json',
		async:false
	})
}