

//====================================================
// No plugin beyond this point.
//====================================================


/*
* Misc Functions
*/

jQuery.fn.toggleText = function (value1, value2) {
    return this.each(function () {
        var $this = $(this),
            text = $this.text();
 
        if (text.indexOf(value1) > -1)
            $this.text(text.replace(value1, value2));
        else
            $this.text(text.replace(value2, value1));
    });
};

/*
* jQuery goes here
*/

$(document).ready(function() {
/* BEGIN
==================================================== */

	/* Flex Slider
	-------------------------------------------------- */
	$('.flexslider').flexslider({
		animation: "fade",
		//pausePlay: "true",
		slideshowSpeed: 9000,
		controlNav: false
	});

	/* Select Menu
	-------------------------------------------------- */	
	// Create the dropdown base
	$("<select />").appendTo("nav");
	// Create default option "Site Menu"
	$("<option />", {
		 "selected": "selected",
		 "value"   : "",
		 "text"    : "Site Menu"
	}).appendTo("nav select");
	// Create default option "Home"
	$("<option />", {
		 "value"   : "/",
		 "text"    : "Home"
	}).appendTo("nav select");
	// Populate dropdown with menu items
	$("nav a").each(function() {
	 var el = $(this);
	 $("<option />", {
			 "value"   : el.attr("href"),
			 "text"    : el.text()
	 }).appendTo("nav select");
	});
	$("nav select").change(function() {
  window.location = $(this).find("option:selected").val();
	});

	
	/* Form Validation
	-------------------------------------------------- */	
	$(".validate").validate({
  		rules: 
				{
    		price:{	required: true,number: true	},
				area:{ required: true,number: true},
				waste:{	required: true,digits: true}
  			}
	}); 
	$(".validate2").validate(); // form validation
	
	
	/* Tabs
	-------------------------------------------------- */	
	var tabs = $('ul.tabs');
	tabs.each(function(i) {
		//Get all tabs
		var tab = $(this).find('> li > a');
		tab.click(function(e) {
			//Get Location of tab's content
			var contentLocation = $(this).attr('href');
			//Let go if not a hashed one
			if(contentLocation.charAt(0)=="#") {
				e.preventDefault();
				//Make Tab Active
				tab.removeClass('active');
				$(this).addClass('active');
				//Show Tab Content & add active class
				$(contentLocation).fadeIn(300).addClass('active').siblings().hide(100).removeClass('active');
			}
		});
	});

	/* Misc Form Usability
	-------------------------------------------------- */
	// Check all for form
	$('.checkall').click(function () {
		$(this).parents('fieldset:eq(0)').find(':checkbox').attr('checked', this.checked);
		$(this).parents('fieldset:eq(0)').find('label').toggleClass('selected');
		var checkALLChecked = $("input.checkall:checkbox:checked").length;
		var totalChecked = $("input:checkbox:checked").length;
		$("p.total span").text(totalChecked - checkALLChecked);
	});
	
	// Highlight selected checkbox items
	$("input[type='checkbox']").change(function() {
  		$(this).closest("label").toggleClass("selected"); 
			var checkALLChecked = $("input.checkall:checkbox:checked").length;
			var totalChecked = $("input:checkbox:checked").length;
			$("p.total span").text(totalChecked - checkALLChecked);
	});
	
	// Visual feedback on form reset 
	$(".reset").click(function(){
			$("button").text(this.checked ? "Restart" : "Continue");
			$("button").toggleClass("orange"); 
			$(this).next().text(this.checked ? "You will restart from the beginning." : "Reset this form and start from the beginning.");
			$("p.total span").toggle();
			$("p.total").fadeToggle('slow');
  });


	/* SUBMITTAL 
	-------------------------------------------------- */
	// Warranty Checkbox
	$("input[type='checkbox'].warranty").change(function() {
  		$(this).parent("label").next("div").fadeToggle();
	});
	
	// Weathertight Warranty Selection
	$("input.ldv").click(function() {
  	$("div.ldv").show();
		$("div.licv").hide();
		$("div.ndl").hide();
		
	});
	$("input.licv").click(function() {
  	$("div.ldv").hide();
		$("div.licv").show();
		$("div.ndl").hide();
	});
	$("input.ndl").click(function() {
  	$("div.ldv").hide();
		$("div.licv").hide();
		$("div.ndl").show();
	});
	
	
	
	/* Disclaimer 
	-------------------------------------------------- */
	$('.agree').click(function() {
		$(this).fadeOut();
		$(this).prev().slideUp('slow', function() {
			// Animation complete.
		})
		$(this).next().fadeIn('slow', function() {
			// Animation complete.
		});
		 
	});
	
	/* Toggle Functions
	-------------------------------------------------- */
	$('.toggle.above').click(function() {
		$(this).toggleText("Show", "Hide"); 
		$(this).toggleClass("show hide");
		$(this).prev().slideToggle('fast', function() {
			// Animation complete.
		});
	});
	
	$('.toggle-below').click(function() {
		$(this).hide(); 
		$(this).next().toggle('slow', function() {
			// Animation complete.
		});
	});
	
	$('.toggle-above').click(function() {
		$(this).toggleText("Show", "Hide"); 
		$(this).toggleClass("show hide");
		$(this).prev().slideToggle('fast', function() {
			// Animation complete.
		});
	});
	
	
	
	
	
	/* Misc Effects
	-------------------------------------------------- */
	$("input[type='checkbox'].single").change(function() {
  		$("p.single").toggleText("single-use", "multi-use");
	});
	
	$( ".datepicker" ).datepicker();
	
	$("form input[type='checkbox']").change(function () {
      $(this).closest('label').effect("highlight", {}, 100);
	});
	
	/* Locations Map
	-------------------------------------------------- */
	$('.locations_map').mobilymap({
		position: '300 5',
		popupClass: 'bubble',
		markerClass: 'point',
		popup: true,
		cookies: false,
		caption: true,
		setCenter: true,
		navigation: true,
		navSpeed: 1000,
		navBtnClass: 'navBtn',
		outsideButtons: '.map_buttons a',
		onMarkerClick: function(){},
		onPopupClose: function(){},
		onMapLoad: function(){}
	});

	
	/* Login Form
	-------------------------------------------------- */
	$("form.login").validate({
	submitHandler: function(form) 
	{
	// Set variable for live element
	var statusElement = $("form.login").children('.status')
						
	statusElement.addClass('loading').text('Validating....').fadeIn(1000);
												
	$.post("scripts/login.php?method=ajax",{ 
					username:$('#username').val(),
					password:$('#password').val(),
					rand:Math.random() 
					} ,function(result)
							
					{
					if(result=='valid') //if correct login detail
						{
						statusElement.fadeTo(200,0.1,function()  //start fading the messagebox
								{
								$(this).addClass('success').html('Logging in.....').fadeTo(900,1,
								function()
									{
									// 
									document.location='/Warranty';
									// 
									});
								});
							}
					else
							{
							statusElement.fadeTo(200,0.1,function() //start fading the messagebox
								{
								$(this).removeClass('loading').addClass('fail').html('Username or Password is incorrect').fadeTo(900,1);
								});
							}
					});
			return false;//not to post the  form physically
			}
	});	
				// end of form stuff

// Contact Form
//-----------------------------------------------------------
$('form.contact ').validate({
	submitHandler: function(form) 
	{
		$('button[type="submit"]').hide(); 
		$('.status').fadeIn('fast').addClass('loading').html('Sending message...');
		$('.contact_fields').find(':input:not(:disabled)').prop('disabled',true);
		$.ajax({
			type : 'POST',
			url : 'scripts/contact.php?method=ajax',
			data: {
				form : $('#form').val(),
				name : $('#name').val(),
				email : $('#email').val(),
				phone : $('#phone').val(),
				company : $('#company').val(),
				message : $('#message').val(),
				register : $('#register').val()
			},
			success: function (html) {              
                //if process.php returned 1/true (send mail success)
                if (html==1) {                  
                    //hide the form
                    //show the success message
                    $('.status').removeClass('loading').addClass('success').text('Message sent.');
                     
                //if process.php returned 0/false (send mail failed)
                } else alert('Sorry, an unexpected error. Please try again later.');               
            } 
						      
        });
				return false;
			}
    }); 
		
// Register Form
//-----------------------------------------------------------
$('form.registration').validate({
	submitHandler: function(form) 
	{
		$('button[type="submit"]').hide(); 
		$('.status').fadeIn('fast').addClass('loading').html('Sending request...');
		$('.contact_fields').find(':input:not(:disabled)').prop('disabled',true);
		$.ajax({
			type : 'POST',
			url : '/scripts/contact.php?method=ajax',
			data: {
				form : $('#form').val(),
				name : $('#name').val(),
				email : $('#email').val(),
				phone : $('#phone').val(),
				company : $('#company').val(),
				message : $('#message').val()
			},
			success: function (html) {              
                //if process.php returned 1/true (send mail success)
                if (html==1) {                  
                    //hide the form
                    //show the success message
                    $('.status').removeClass('loading').addClass('success').text('Message sent.');
                     
                //if process.php returned 0/false (send mail failed)
                } else alert('Sorry, an unexpected error. Please try again later.');               
            } 
						      
        });
				return false;
			}
    }); 



/* END
==================================================== */

});

function UpdateTableHeaders() {
       $(".persist-area").each(function() {
       
           var el             = $(this),
               offset         = el.offset(),
               scrollTop      = $(window).scrollTop(),
               floatingHeader = $(".floatingHeader", this)
           
           if ((scrollTop > offset.top) && (scrollTop < offset.top + el.height())) {
               floatingHeader.css({
                "visibility": "visible"
               });
           } else {
               floatingHeader.css({
                "visibility": "hidden"
               });      
           };
       });
    }
    
    // DOM Ready      
    $(function() {
    
       var clonedHeaderRow;
    
       $(".persist-area").each(function() {
           clonedHeaderRow = $(".persist-header", this);
           clonedHeaderRow
             .before(clonedHeaderRow.clone())
             .css("width", clonedHeaderRow.width())
             .addClass("floatingHeader");
             
       });
       
       $(window)
        .scroll(UpdateTableHeaders)
        .trigger("scroll");
       
    });
