var slideshowInterval;
// Hide all sub menus - No Javascript and the all show	
// http://www.jslint.com/

$.pageStart = function() {
	

	//http://buildinternet.com/2009/03/sliding-boxes-and-captions-with-jquery/
	//Caption Sliding (Partially Hidden to Visible)
	$('.CaptionBox').hover(function(){
		$(".cover", this).stop().animate({top:'50px'},{queue:false,duration:160});
	}, function() {
		$(".cover", this).stop().animate({top:'122px'},{queue:false,duration:260});		
	});	

	$('.IndexBox').hover(function(){		
		$(this).find(".IndexText").stop().animate({top:'0px'},{queue:false,duration:260});
		$(this).find(".IndexTextBox").stop().animate({opacity: 0.85}, { queue:false, duration:260 });
	}, function() {
		$(this).find(".IndexText").stop().animate({top:'-130px'},{queue:false,duration:660});
		$(this).find(".IndexTextBox").stop().animate({opacity: 0.0}, { queue:false, duration:660 });		
	});		
	
	$('.IndexTextBox').fadeTo(1,0.0);	
	
	// add in input box for tracking source page for queries
	$('.SourcePage').replaceWith("<input type=\"hidden\" name=\"SourceURL\" id=\"SourceURL\" value=\"" + window.location.pathname + "\">");
	
	// Change link in feedback button to ID of Feedback DIV
	$("#Feedback").attr('href', '#feedbackdiv');
	
	$("#Feedback").fancybox({
		'href'			: '#feedbackdiv', // Force to use this ID cause ie6 sucks!!!
		'autoScale'     : false,
		'transitionIn'	: 'elastic',
		'transitionOut'	: 'elastic',
		'easingIn'      : 'easeOutBack',
		'easingOut'     : 'easeInBack',
		'overlayOpacity': 0.7,
		'overlayColor'  : '#FFF'		
	});		
		
	$("a.group").fancybox({ 
		'titlePosition': 'inside',
		'zoomSpeedIn': 300,
		'zoomSpeedOut': 300,
		'overlayOpacity': 0.7,
		'overlayColor': '#FFF',
		'transitionIn'	: 'elastic',
		'transitionOut'	: 'elastic',
		'easingIn'      : 'easeOutBack',
		'easingOut'     : 'easeInBack'
	});
	
	var d='digitex.co.nz';
	var e='in' + 'fo';
	$("#contactEmail").append('<a href=\"mailto:' + e + '@' + d + '\">' + e + '@' + d + '</a>');
			
	$.setStarRating('hover-starA');
	$.setStarRating('hover-starB');
	$.setStarRating('hover-starC');
	$.setStarRating('hover-starD');
	
	// *************** FEEDBACK FORM *************
	/*if ($('.slide-out-div').size() > 0){
		isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
		
		// IE 6 is a pile of crap so dont bother trying to fix this - just dont show in ie 6
		if (!isIE6){
			// dont run in ie6
			$('.slide-out-div').show();
			// only run this is feedback element is on the page
			$('.slide-out-div').tabSlideOut({
				tabHandle: '.handle',                          //class of the element that will be your tab
				pathToTabImage: 'menu/feedbacktop2.gif',        //path to the image for the tab *required*
				imageHeight: '27px',                           //height of tab image *required*
				imageWidth: '100px',                           //width of tab image *required*    
				tabLocation: 'top',                            //side of screen where tab lives, top, right, bottom, or left
				speed: 300,                                    //speed of animation
				action: 'click',                               //options: 'click' or 'hover', action to trigger animation
				leftPos: '675px',                              //position from the top
				fixedPosition: true                            //options: true makes it stick(fixed position) on scroll
			});

			$.setStarRating('hover-starA');
			$.setStarRating('hover-starB');
			$.setStarRating('hover-starC');
			$.setStarRating('hover-starD');
		}
	}			*/	
};


function Right(str, n){
    if (n <= 0){
       return '';}
    else if (n > String(str).length)
       {return str;}
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

//http://www.queness.com/post/152/simple-jquery-image-slide-show-with-semi-transparent-caption

function UpdateEnquiry(element){
	$.ajax({
		type: 'post',
		url: 'updateenquiry.php',
		dataType: 'html',
		data: {action:  $(element).attr('action'), pid: $(element).attr('pid')},
		success: function (html) {
			if (html == '#empty')
			{	
				// hide the custom enquiry list
				checkElement = $('#EnquiryCart');
				checkElement.slideUp('normal',function(){$('#GeneralEnquiry').slideDown('slow');}); 				
				checkElement.html('');		
			}
			else
			{	
				// hide the custom enquiry list
				checkElement = $('#EnquiryCart');
				if (checkElement.html(html)=='') {					
					checkElement.hide(); //make sure its hidden
				}
				checkElement.html(html);
				
				//if ( checkElement.is(':visible') ) { checkElement.slideDown('normal', function() {$('#GeneralEnquiry').slideUp('slow'); }); }
				checkElement.slideDown('normal', function() {$('#GeneralEnquiry').slideUp('slow'); });	
				
				// if its the add to cart button then show animation
				if ($(element).attr('id')=='Add_To_Cart') { 
					animateaddbutton();
				}
				
				$('#Add_To_Cart').addClass('RequestQuoteGrey'); 
			}
		}
	});
}

$.formStart = function(){
	
	// Add click event to Ajax style update to cart
	$('#Add_To_Cart').click( function(){
		UpdateEnquiry(this);	
		return false;
	});
	
	$('#SendForm').click( function(){
		$('#FormQuote').submit();	
		return false;
	});		
	
	$('#SubmitButton').hide();
	$('#SendForm').show();			

	// validate signup form on keyup and submit
	if ( $("#FormQuote").size() > 0 ){
		var validator = $("#FormQuote").validate({
			rules: {
				Name: "required",
				Email: {
					required: true,
					email: true
				},
				Details: "required"
			},
			messages: {
				Name: "Enter your name",
				Phone: "Enter your Phone Number",
				Email: {
					required: "Please enter a valid email address",
					minlength: "Please enter a valid email address"
				},
				Details: "Please enter a request"
			}//,					
			// specifying a submitHandler prevents the default submit, good for the demo
			//submitHandler: function() {
			//	alert("submitted!");
			//}
		});	
	}
};


function extractPageName(hrefString)
{
	
	var arr = hrefString.split('.');
	if (arr.length == 1) {return ('hahaha');}
	
	/// Check to see if the url has a query string by searching for the question mark		
	var hasquestion  = hrefString.indexOf('?');
	if (hasquestion == '-1')
	{
		arr = arr[arr.length-2].split('/');
		return arr[arr.length-1].toLowerCase();
	}
	else
	{
		// has ?
		arr = arr[0].split('/');
		return arr[arr.length-1].toLowerCase();
	}
}

$.menustart = function(meniID, menuhref, setHome) {
	
	// hide submenus and add in classes for shadows
	$('#' + meniID +' ul').hide();	
	$('#' + meniID +' ul li:first-child').addClass("dmenuFirst");
	$('#' + meniID +' ul li:last-child').addClass("dmenuLast");
	
	// Add toggles boxes to every link with children
	$('#' + meniID + ' > li > a').each(function() {  
		if ($(this).next().size()  >0){
			$(this).prepend("<div class=\"dmenu_Expand\"></div>");
		}
	});
		
	// Find matching link in menu to current page link
	var menulink;
	var hrefString = document.location.href ? document.location.href : document.location;
	var pagenameString ;
		
	if (menuhref === null ||menuhref == '' ){
		pagenameString = extractPageName(hrefString); 
	}
	else {
		pagenameString = menuhref.toLowerCase(); 
	}
	
	var linknameString;		
	var found = false;
	$('#' +meniID +' a').each(function() {		
		linknameString = extractPageName($(this).attr('href'));
		//alert("|" + $(this).attr('href') + "|");
		if (linknameString == pagenameString) {
			menulink = $(this);
			found=true;
			return false;
		}
	});
	
	// no matching links then select home page link
	if (!found && setHome) {
		menulink = $('#' +meniID + ' a:first');
		found=true;
	}
	
	if (found){
		// highlight show currently selected menu
		if (menulink.parent().parent().attr('id') == 'dmenu') {
			// this is a parent
			menulink.next().show();
			menulink.find('div').addClass('dmenu_Collapse');
			menulink.addClass('selected');
		}
		else {
			// Its is a child then hilight page
			menulink.addClass('selectedpage');
			menulink.parent().parent().show();
			menulink.parent().parent().parent().find('a div').addClass('dmenu_Collapse');	
			//menulink.parent().parent().parent().find('a:first').addClass('selected');
		}	
		
		QuoteLink = $("#LinkButton A").attr('href');
		if (QuoteLink !== null){
			if ( QuoteLink.indexOf("?") == -1 ){
				$("#LinkButton A").attr('href', QuoteLink + "?pge=" + pagenameString);
			} else {
				$("#LinkButton A").attr('href', QuoteLink + "&pge=" + pagenameString);
			}
		}
	}
		
	// add function to show and hide divs
	$('#' + meniID +' div').click(function() {
		var checkElement = $(this).parent().next();
		if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
			checkElement.slideUp('normal');
			$(this).removeClass('dmenu_Collapse');
			$(this).addClass('dmenu_Expand');
			return false; // Do not follow link
		}	
		if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
			//$('#dmenu ul:visible').slideUp('normal');
			checkElement.slideDown('normal');
			$(this).removeClass('dmenu_Expand');
			$(this).addClass('dmenu_Collapse');
			return false; // Do not follow link
		}
	});	
	
	return found;	
};


$.tabs = function(selector, start) {
	$(selector).each(function(i, element) {
		$($(element).attr('tab')).css('display', 'none');
		
		// remove links to specefic pages
		$(element).removeAttr("href");
		
		$(element).click(function() {
			$(selector).each(function(i, element) {
				$(element).removeClass('selected');
				
				$($(element).attr('tab')).css('display', 'none');
			});
			
			$(this).addClass('selected');
			
			$($(this).attr('tab')).css('display', 'block');
		});
	});
	
	if (!start) {
		start = $(selector + ':first').attr('tab');
	}

	$(selector + '[tab=\'' + start + '\']').trigger('click');
};



function animateaddbutton(){
	var image = $('#Add_To_Cart').offset();
	var cart = $('#EnquiryCart').offset();

	//$('#Add_To_Cart').before('<div class="RequestQuote" id="temp" style="position: absolute; top: ' + image.top + 'px; left: ' + image.left + 'px;" />' +  $('#Add_To_Cart').html() + "</div>");
	$('#Add_To_Cart').before('<div class="RequestQuote" id="temp" style="position: absolute; top: ' + image.top + 'px; left: ' + image.left + 'px; z-index:2000;" /></div>');
	
	//params = {
	//	top : cart.top + 'px',
	//	left : cart.left + 'px',
	//	opacity : 0.0,
	//	width : $('#module_cart').width(),
	//	heigth : $('#module_cart').height()
	//};
	
	params = {
		top : cart.top + 'px',
		left : cart.left + 'px',
		opacity : 0.0
	};	
	
	$('#temp').animate(params, 500, false, function () {$('#temp').remove(); });
}
 
function slideShow() {  

	//Set the opacity of all images to 0  
	$('#slideshow a').css({opacity: 0.0});  
	
	//Get the first image and display it (set it to full opacity)  
	$('#slideshow a:first').css({opacity: 1.0});  
	
	//Resize the width of the caption according to the image width  
	$('#slideshow .caption').css({width: $('#slideshow a').find('img').css('width')});  
	
	//Get the caption of the first image from ALT attribute and display it  
	$('#slideshow .contentTop H3').html($('#slideshow a:first').find('img').attr('title'));  
	$('#slideshow .contentTop P').html($('#slideshow a:first').find('img').attr('alt'));  
	
	//Call the runslideshow function to run the slideshow, 5000 = change to next image after 5 seconds  
	slideshowInterval = setInterval('runslideshow()',5000);  
	
	//$("#slideshow a").each( function( intIndex ){
	//	this								 
	//});
						   
	// create HTML of selectors based on image ID's
	var strhtml ='';					   
	$('#slideshow a').each( function( intIndex ){									   
		strhtml = '<li rel="' +  $( this ).attr('id') + '"></li>' + strhtml ;	
	});	
	
	//add selectors
	$('.slideshowSelector').append(strhtml);	

	//hilight selector
	$('.slideshowSelector Li' + '[rel=\'' + $('#slideshow a:first').attr('id') + '\']').addClass('selected');	
	
	// add hover function to pause and start show
	$(".slideshowSelector Li").hover(function(){
		clearInterval(slideshowInterval);
		runslideshow($(this).attr('rel'));	
	}, function() {
		slideshowInterval = setInterval('runslideshow()',5000);  
	});
}
   
function runslideshow(slideid) {  
	
	//if no IMGs have the show class, grab the first image  
	var current = ($('#slideshow a.show')?  $('#slideshow a.show') : $('#slideshow a:first'));  
	
	var next;
	var proceed = true;
	if (slideid != null){	
		next = $('#' + slideid);
		if(next.hasClass('show')) 
			{proceed=false;}
	} else {
		//Get next image, if it reached the end of the slideshow, rotate it back to the first image  
		next = ((current.next().length) ? ((current.next().hasClass('caption'))? $('#slideshow a:first') :current.next()) : $('#slideshow a:first'));  
	}
	
	if (proceed){
		
		//Get next image caption  
		var caption = next.find('img').attr('alt'); 
		var title = next.find('img').attr('title'); 
		
		// Stop but finish any current animations.
		$('#slideshow .caption').stop(true, false);	
		next.stop(true, false);	
		next.stop(true, false);
		
		//Set the fade in effect for the next image, show class has higher z-index  
		next.css({opacity: 0.0})  
		.addClass('show')  
		.animate({opacity: 1.0}, 1000);  
		
		//Hide the current image  
		current.animate({opacity: 0.0}, 1000)  
		.removeClass('show');  
		
		//Set the opacity to 0 and height to 1px  	
		$('#slideshow .content').animate({opacity: 0.0}, { queue:false, duration:300 });
		
		//var top = $('#slideshow').css('height');
		//$('#slideshow > .caption').animate({top: '255px'}, { queue:true, duration:300 }); 
		$('#slideshow > .caption').animate({top: $('#slideshow').css('height')}, { queue:true, duration:300 }); 
		
		$('.slideshowSelector Li').removeClass('selected');		
		//highlight key
		$('.slideshowSelector Li' + '[rel=\'' + next.attr('id') + '\']').addClass('selected');

		//Display the content  
		if (title != '' && title != null ) {setTimeout ('setCaption(\'' + title + '\',\'' + caption + '\');', 500);}
	}
}  

function setCaption(title,caption){
	$('#slideshow .contentTop H3').html(title); 
	$('#slideshow .contentTop P').html(caption); 
	
	//Animate the caption, opacity to 0.7 and heigth to 100px, a slide up effect  
	$('#slideshow .content').animate({opacity: 0.8}, { queue:false, duration:500 } );
	$('#slideshow > .caption').animate({top: '190px'},{ queue:true, duration:500 } );  
}

$.setStarRating = function(id){
	 // ID = Id pf parent DIV
	 $('#' + id + ' Input').addClass(id);
			   
	 $('.' + id).rating({
	  focus: function(value, link){
		//var tip = $('#hover-starA span.hover-text');
		var tip = $(this).siblings('span.hover-text');
		tip[0].data = tip[0].data || tip.html();
		tip.html(link.title || 'value: ' + value);
	  },
	  blur: function(value, link){
		var tip = $(this).siblings('span.hover-text');
		tip.html(tip[0].data || '');
	  },
	  callback: function(value, link){
			//var tip = $(this).siblings('span.hover-text');
			var tip = $('#' + id + ' span.hover-text');
			if (value==''){
				tip[0].data = '&nbsp;';  	
			} else {
				tip[0].data = link.title || '';  
			}
			tip.html(tip[0].data);		
	  }
	 });
};