/*
 *
 *	Dream Cars Motor Company
 *
 *	Javascript Functions
 *	
 *	written by Ronan Donniou for Conflicting Pixels
 *	Functions are written for JQuery (Ver 1.4.2 min)
 *	No other Library required unless otherwise stated. 
 *
 */


/*
 *	function is_valid_email(email)
 *
 *	check email valid format	
 *	@input : email(string) to check format : [A-Z0-9_.-] @ [a-z]
 *	@output : true / false
*/
function is_valid_email(email)
{
	var EmailRE=/^[a-z0-9._-]+@+[a-z0-9._-]+\.+[a-z]{2,4}$/i;
	if(!EmailRE.test(email)){return false;}
	return true;
}

/*
 *  function is_numeric()
 *
 *	check is input var is numbers only : numeric only with coma
 *  @input  : mixed var to be checked
 *  @output : bool
 */
function is_numeric( mixed_var ) {
	// RegEx numeric only with coma
	var reg1 = new RegExp(/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/);
	if(!reg1.test(mixed_var)){return false;}
	return true;
}

/*
 *	function make_full_link(evt,el)
 *
 *	based on a href tag, add title attr cancel link defaut behavior (e.g. navigation) and modify to open into into new window
 *	@input : event, element
 *	@output : return false (cancel behavior)
 */
	function make_full_link(el)
	{
		lnk = el.attr('title');
		el.attr('title',lnk+' - (opens in a new window)');
		el.bind('click',function(event){event.preventDefault(); window.open($(this).attr('href')); return false;});
	}



/*
 *	function chech_car_form()
 *
 *	check registration form = all fields non empty
 *	@input : user inputs
 *	@output : ok: submit form / ko: error message
*/
	function check_car_form($frm_id){
		$ok = true;
			$('#'+$frm_id+' input.required:text').each(function(){
								 if( jQuery.trim( $(this).attr('value')) == ""  ){
									 $ok = false;
								 }
			 });
			$('#'+$frm_id+' textarea.required').each(function(){
								 if( jQuery.trim( $(this).attr('value')) == ""  ){
									 $ok = false;
								 }
			 });
			
			if( !(is_numeric( $('#mileage').attr('value') ) ) ){$ok = false;}
		return $ok;
	}



/*
 * function mycarousel_initCallback(carousel)
 * We use the initCallback callback
 * to assign functionality to the controls
 *
 * see http://sorgalla.com/jcarousel/ for more info
 *
 * @Require : jCarousel lib for jQuery
 */

function mycarousel_initCallback(carousel) {
    jQuery('#slideshow-next').bind('click', function() {
        carousel.next();
        return false;
    });
 
    jQuery('#slideshow-prev').bind('click', function() {
        carousel.prev();
        return false;
    });

	// Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(
			function() {carousel.stopAuto();},
			function() {carousel.startAuto();
    });
};






function send_callback_request(evt){
	evt.preventDefault();

		  	$contact=	$('#icontact').val();
			$email	=	$('#iemail').val();
	  		$phone	=	$('#iphonen').val();
			$time	=	$('#itime').val();

	if( $contact == '' || $email == '' || $phone == '' || $time == '' ){
		alert('Please fill all Form Fields'); return false;
	}
	if( ! ( is_valid_email(  $email ) ) ){
		alert('Please fill a valid email address'); return false;
	}
	$('#frm_call_back').html('<p class="req_fdb"><img src="'+$base_url+'images/ajax-loader.gif" alt="Processing" /></p>');

	
	$.ajax({
	  url: $base_url+'/async/call_back_request',
	  type: 'POST',
	  data: {
		  	'contact'	:	$contact,
			'email'		:	$email,
	  		'phone'		:	$phone,
			'time'		:	$time
			},
	  success: function(data) {
			if(data == 'TRUE'){
				$('#dbg').html(data);
				$('#frm_call_back').html('<p class="req_fdb">Thank You.<br/>Your request has ben taken into account.<br/>We will call back very soon.</p>');
			}else{
				$('#frm_call_back').html('<p class="req_fdb">Error<br/>Please refresh and try again.</p>');
			}
	  },
	  error:function(data) {alert('An error has occured.\nPlease try again');}
	});	

	
	
}



/*
	function init($page)
	according to param $page init the DOM behaviors
	1rs we can have common behaviors like external links
	2nd specifice behaviors param is body id.
*/
	function init($page)
	{
		// COMMONS
		// external links
//		$(".external").each(
//			function(event){
//				make_full_link(event,$(this));
//			}
//		);		
		
		$('.call_back').click(function(event){
									   	  event.preventDefault();
										  $('#frm_call_back').slideToggle()
										   });
		$('#frm_call_back').submit( function(event){event.preventDefault();  send_callback_request(event); });
//	 PAGE BASED
		switch ($page)
		{
			
			
			case 'home' : 
				 /* 
				  *	Require :  jCarousel lib for jQuery
				  * http://sorgalla.com/jcarousel/
				  */			
				$('.external').each( function(){ make_full_link($(this));});
				// Carousel Init
					jQuery("#slideshow").jcarousel({
						scroll: 1,
						wrap: 'circular',
						auto: 3,						
						initCallback: mycarousel_initCallback,
						buttonNextHTML: null,
						buttonPrevHTML: null
					});
					
				 /* 
				  *	Require : jquery.tweet.js lib for jQuery
				  * http://tweet.seaofclouds.com/
				  */
				$("#newsfeed").tweet({
					username: "Drivingblog",
					join_text: "auto",
					avatar_size: 32,
					count: 3,
					auto_join_text_default: "", //"I said,", 
					auto_join_text_ed: "", //"we",
					auto_join_text_ing: "", //"we were",
					auto_join_text_reply:"", // "we replied to",
					auto_join_text_url: "", //"we were checking out",
					loading_text: "loading tweets..."
				});
			break; // case home
			


			case 'admin_cars_edit':
				//edit button behavior
				$('#edit_car').html('Edit')
							  .attr('title','Edit')
							  .bind('click',
									function(){
										$('.disabled').attr('disabled','').removeClass('disabled');
										$('#make').attr('disabled','disabled');
										$(this).unbind('click')
											   .html('Update')
											   .attr('title','Update')
											   .bind('click',function(){$('#frm_add_car').submit();});
									  }
								);
							  
				$('#delete_car').bind('click',
									  	function(event){
											event.preventDefault();
											yn = confirm('Delete this car ?\nThis cannot be undone.\nProceed ?');
											if(yn){$('#frm_del_car').submit()};
											
										}
									  )
							  
				// from check on form submit
				$('#frm_add_car').submit(function(event){
													$('.errormsg').slideUp('fast');
													if( !check_car_form('frm_add_car') ){
														event.preventDefault();
														$('.errormsg').slideDown();
													}
												}
										);
			break; //case admin_cars_edit



			case 'admin_cars_add':
				$('.disabled').attr('disabled','').removeClass('disabled');
				$('#make').attr('disabled','disabled');
				//edit button behavior
				$('#edit_car').html('Add')
							  .attr('title','Add')
							  .bind('click',function(){$('#frm_add_car').submit();}
							);
				// from check on form submit			  
				$('#frm_add_car').submit(function(event){
													$('.errormsg').slideUp('fast');
													if( !check_car_form('frm_add_car') ){
														event.preventDefault();
														$('.errormsg').slideDown();
													}
												}
										);
			break; // case admin_cars_edit
			
			
		 case 'car_detail'	:
		 	$('#backtolist').find('a').click(function(){ history.go(-1); return false;});
			// page init
			$('#thumbs img').css({'opacity':'0.5','cursor':'pointer'});//init all opacity 50%
			$('#thumbs img:first').css({'opacity':'1','cursor':'default'});//set first img 100%
			//mousevor behavior, set to 75% if not @ 100%, i.e. if not clicked
			$('#thumbs img').mouseover(function(){
					if( $(this).css('opacity') != 1 ){	$(this).css({'opacity':'0.75','cursor':'pointer'});}
				});
			//mouseout , set to 50% if 75%, i.e. if not clicked
			$('#thumbs img').mouseout(function(){
					if( $(this).css('opacity') ==0.75 ){$(this).css({'opacity':'0.5','cursor':'pointer'});}
				});
			// link behavior
			$('#thumbs img').click(function(){
					var toshow = $base_url+'images/cars/'+$(this).attr("alt");
					if($('#big img').attr('src') != toshow){
						$('#thumbs img').css({'opacity':'0.5','cursor':'pointer'});
						$(this).css({'opacity':'1','cursor':'default'});
						$('#big img').fadeOut('slow',function(){$(this).attr('src',toshow);});
						$("#big img").load(function(){$(this).fadeIn('slow');});
					}
					return false;
			});
			// preload
		 break;
		 
		 
		case 'stock'	:
			// drop down
			$('#filter_menu li').hover(
								function(){ $(this).find('.sec').stop(true,true).slideDown('fast');},
								function(){ $(this).find('.sec').stop(true,true).slideUp('fast'); }
						);
		break;
		
		
		case 'admin_users' :
			$('#cancel').click(function(){	self.location.href= $base_url+'admin/users/';	}	);
			$('#uform').submit(function(){
									   $('.errormsg').slideUp('fast');
									   if(  ( jQuery.trim( $('#login').val() ) ==  '' )  || ( jQuery.trim( $('#password').val() ) == '' ) ){
										   $('.errormsg').slideDown();
										   return false;
									   }
								   }
								);
		break;
		
		case 'admin_makes' :
			$('#cancel').click(function(){	self.location.href= $base_url+'admin/makes/';	}	);
			$('#uform').submit(function(){
									   $('.errormsg').slideUp('fast');
									   if(  ( jQuery.trim( $('#name').val() ) ==  '' ) ){
										   $('.errormsg').slideDown();
										   return false;
									   }
								   }
								);
		break;
		
		case 'ask' :
			$('.q_topic').click(function(event){
								   event.preventDefault();
								//	if( !$(this).parent('div').hasClass('xpd') ){
								//	   $('.xpd').removeClass('xpd').addClass('strc').children('div').stop(true,true).slideUp();
									   $(this).parent('div')./*removeClass('strc').addClass('xpd').*/children('div').stop(true,true).slideToggle();
								//	}
						  });
			$('#submit_q').click(function(event){
									$do = true;
									event.preventDefault();
									$('.required').each(function(event){
															if( $(this).val() =='') {
																alert('Please fill all required fields');
																$do =  false;
																return false;
															}
														});
									if($do){ $('#ask_form').submit() ; }
								});
		break;
		
		
	}
}
