//
// NAVIGATION
//

jQuery(document).ready(function(){

	if(!$.browser.msie)
	{
		jQuery('.menuhover').removeClass('menuhover');
		
		jQuery('#navigation ul').find('ul').css("opacity", "0").hide();
		
		jQuery('#navigation').find('li').hover(
			function() {
				jQuery(this).find('ul:first').stop().show().animate({
				opacity: '1'
				}, 350); },
			function() {
				jQuery(this).find('ul:first').stop().animate({
				opacity: '0'
				}, 350, function(){ jQuery(this).hide(); });
			jQuery(this).find('ul:first').find('ul').hide();
		});
	}
});


// 
// IMAGE LOADER
//

function gallery_img_hover(id) {
	jQuery(".rollover").css( {backgroundPosition: "276px 103px"} );

	jQuery(id).hover(
		function() {
				jQuery(this).find('.hover_fade').stop().animate({opacity:0.4},400);
				jQuery(this).find('.rollover').stop().animate( {backgroundPosition:"228px 103px"}, 500);
			},
			function() {
				jQuery(this).find('.hover_fade').stop().animate({opacity:1},400);
				jQuery(this).find('.rollover').stop().animate({backgroundPosition:"276px 103px"}, 500);
			}
	);	
}

jQuery("<img>").attr("src", "/wp-content/themes/Deluxe/images/loader.gif");
jQuery("<img>").attr("src", "/wp-content/themes/Deluxe/images/zoom.png");
jQuery("<img>").attr("src", "/wp-content/themes/Deluxe/images/play.png");
jQuery("<img>").attr("src", "/wp-content/themes/Deluxe/images/link.png");

jQuery(document).ready(function() {
	
	// change this to get a different effect
	var waitForAnimBeforeLoad = false;
	
	var images = jQuery("span.image_holder_span img", "div[id^='image_holder_']");
	images.remove();
	jQuery("span.image_holder_loading", "div[id^='image_holder_']").css({ 'display': 'inline' });
	
	// we start the loading loop
	if(images.length > 0)
		loadNextImage(0, images.length);
		
	function loadNextImage(index, count)
	{
		if(jQuery(images[index]).attr('src') == "")
		{
			// if image src is empty, we remove the loading image and move on
			jQuery("span.image_holder_loading", "#image_holder_" + index).remove();
			
			if(index < count - 1)
				loadNextImage(index + 1, count);
		}
		else
		{
			var img = new Image();

			jQuery(img).load(function () {
				// on load, we remove the loading image and fade in the real image
				jQuery("span.image_holder_loading", "#image_holder_" + index).remove();
				jQuery(this).css('display','none');
				
				jQuery("span.image_holder_span", "#image_holder_" + index).append(this);
				
				if($(this).parents(".galleryItem3").length == 0)
				{
					$(this).width($("#image_holder_" + index).width());
					$(this).height($("#image_holder_" + index).height());
				}
				
				jQuery(this).fadeIn(500, function()
										{ 											
											setup_hover('#image_holder_' + index);											
											if(waitForAnimBeforeLoad)
											{
												if(index < count - 1)
													loadNextImage(index + 1, count);
											}
										});
				if(!waitForAnimBeforeLoad)
				{
					if(index < count - 1)
						loadNextImage(index + 1, count);
				}
			}).error(function () {
				// if there's an error, we remove the loading image and move on			
				jQuery("span.image_holder_loading", "#image_holder_" + index).remove();
	
				if(index < count - 1)
					loadNextImage(index + 1, count);					
			}).attr('src', jQuery(images[index]).attr('src'));			
		}
	}
	
	function setup_hover(id) {
		var obj = jQuery(id);
		if(obj.hasClass("tmp_rollover_zoom"))
			obj.toggleClass("tmp_rollover_zoom rollover_zoom").find("img").addClass('hover_fade');
		if(obj.hasClass("tmp_rollover_play"))
			obj.toggleClass("tmp_rollover_play rollover_play").find("img").addClass('hover_fade');
		if(obj.hasClass("tmp_rollover_link"))
			obj.toggleClass("tmp_rollover_link rollover_link").find("img").addClass('hover_fade');

		var hcenter = (obj.width() - 64)/2;
		var vcenter = (obj.height() - 64)/2;		

		jQuery(id).hover(
			function() {
					jQuery(this).stop().css({backgroundPosition: (hcenter - 30) + "px " + vcenter + "px" }).animate({backgroundPosition: (hcenter) + "px " + vcenter + "px" }, 400);
					jQuery(this).find('.hover_fade').stop().animate({opacity: 0.4}, 400);
				},
				function() {
					jQuery(this).stop().animate({backgroundPosition: (hcenter + 30) + "px " + vcenter + "px" }, 400);
					jQuery(this).find('.hover_fade').stop().animate({opacity: 1}, 400);
				});
	}

});


//
// SLIDE DOWN
//

$(document).ready(function()
{
	$(".hiddenContent div").hide();    
    $('.hiddenContent a, .visibleContent a').click(function () {
		if($("div", $(this).parent()).is(":visible"))
			$("span", $(this)).html("+");
		else
			$("span", $(this)).html("-");
		slideToggle("div", $(this).parent());
    });
	
	function slideToggle(el, context){
		var $el = $(el, context), height = $el.data("originalHeight"), visible = $el.is(":visible");
		var ptop = $el.data("originalPTop"), pbot = $el.data("originalPBot");
		bShow = !visible;
		
		if( !height || !ptop || !pbot){
			height = $el.show().height();
			$el.data("originalHeight", height);
			
			ptop = $el.css("padding-top");
			$el.data("originalPTop", ptop);
			
			pbot = $el.css("padding-bottom");
			$el.data("originalPBot", pbot);			

			if( !visible ) 
				$el.hide().css({height: 0});
		}
		
		// expand the knowledge (instead of slideDown/Up, use custom animation which applies fix)
		if( bShow ){
			$el.show().animate({height: height, "padding-top": ptop, "padding-bottom": pbot}, {duration: 250});
		} else {
			$el.animate({height: 0, "padding-top": 0, "padding-bottom": 0}, {duration: 250, complete:function (){
				$el.hide();
			}});
		}
	}
});

//
// INPUT BLUR
//

$(document).ready(function()
{
    $(".defaultText").focus(function(srcc)
    {
        if ($(this).val() == $(this)[0].title)
        {
            $(this).removeClass("defaultTextActive");
            $(this).val("");
        }
    });
    
    $(".defaultText").blur(function()
    {
        if ($(this).val() == "")
        {
            $(this).addClass("defaultTextActive");
            $(this).val($(this)[0].title);
        }
    });
    
    $(".defaultText").blur();        
});

//
// IMAGE SLIDE
// 

$(function() {
	$('ul.galleryItem3 li').hover(function(){
		$(this).find('img').animate({top:'170px'},{queue:false,duration:500});
	}, function(){
		$(this).find('img').animate({top:'0px'},{queue:false,duration:500});
	});
});

//
// VALIDATE FORMS
//

jQuery(document).ready(function(){
	var items = jQuery('#imageList li');
	if(items.length != 0)
	{
		var w = items.width() + parseInt(items.css("padding-left").replace("px", "")) + parseInt(items.css("padding-right").replace("px", ""));
		var m = (960/items.length - w)/2;
		if(m > 0)
			jQuery('#imageList li').css("margin", "0px " +  m + "px");
	}
	$(".validate_button_comment").attr('onclick', '').click(function(e) {
		var valid = true;
		
		$(this).parent().find('.validate_entry input, .validate_entry textarea').each( function () { 
			if($(this).val().trim() == '' || $(this).val().trim() == $(this).attr('title').trim())
			{
				highlightInputField($(this));
				//$(this).stop().focus();//animate({ backgroundColor: "#FC1959", color: "#FFFFFF"}, 300);
				valid = false;
			}
		});
		
		$(this).parent().find('.validate_email input').each( function () { 
			if($(this).val().trim() == '' || $(this).val().trim() == $(this).attr('title').trim() || !emailCheck($(this).val().trim()))
			{
				highlightInputField($(this));
				//$(this).stop().focus();//.animate({ backgroundColor: "#FC1959", color: "#FFFFFF"}, 300);
				valid = false;
			}
		});
		
		if(valid)
		{
			$('input, textarea').each( function () { 
				if($(this).val().trim() == $(this).attr('title').trim())
					$(this).val('');
			});				
		
			this.parentNode.submit();
		}
	});
	
	var def_sumbit_action = $(".validate_button_contact").attr('onclick');
	$(".validate_button_contact").attr('onclick', '').click(function(e) {
		var valid = true;
		
		$(this).parent().find('.validate_entry input, .validate_entry textarea').each( function () { 
			if($(this).val().trim() == '' || $(this).val().trim() == $(this).attr('title').trim())
			{
				highlightInputField($(this));
				valid = false;
			}
		});
		
		$(this).parent().find('.validate_email input').each( function () { 
			if($(this).val().trim() == '' || $(this).val().trim() == $(this).attr('title').trim() || !emailCheck($(this).val().trim()))
			{
				highlightInputField($(this));
				valid = false;
			}
		});
		
		if(valid)
		{
			$('input, textarea').each( function () {  
				if($(this).val().trim() == $(this).attr('title').trim())
					$(this).val('');
			});				
		
			def_sumbit_action();
		}
	});	
	
});

function sendContactRequest(submitformid, url, toemail, buttonid, loadingid, successid)
{	
	var params = 'toemail=' + toemail;
	$("#" + submitformid).find("input, textarea").each( function() { if($(this).val() != $(this).attr('title')) params += '&' + $(this).attr('name') + '=' + $(this).val(); });
	
	xmlhttp = GetXmlHttpObject();
	xmlhttp.onreadystatechange = function() {if (xmlhttp.readyState == 4)
											{
												if(xmlhttp.responseText.indexOf('mailsentok') >= 0)
												{
													$(loadingid).hide();
													$(successid).show();
												}
												else
												{
													$(loadingid).hide();
													$(buttonid).show();
												}
											}
										};
	xmlhttp.open("POST", url, true);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", params.length);
	xmlhttp.setRequestHeader("Connection", "close");
	xmlhttp.send(params);
	$(buttonid).hide();
	$(loadingid).show();
}

function GetXmlHttpObject()
{
	if (window.XMLHttpRequest)
	{
		return new XMLHttpRequest();
	}
	if (window.ActiveXObject)
	{
		return new ActiveXObject("Microsoft.XMLHTTP");
	}
	return null;
}

function emailCheck (emailStr) {

var emailPat=/^(.+)@(.+)$/;
var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
var validChars="\[^\\s" + specialChars + "\]";
var quotedUser="(\"[^\"]*\")";
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
var atom=validChars + '+';

/* The following string represents one word in the typical username.
For example, in john.doe@somewhere.com, john and doe are words.
Basically, a word is either an atom or quoted string. */

var word="(" + atom + "|" + quotedUser + ")";

// The following pattern describes the structure of the user

var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

/* The following pattern describes the structure of a normal symbolic
domain, as opposed to ipDomainPat, shown above. */

var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

/* Finally, let's start trying to figure out if the supplied address is valid. */

/* Begin with the coarse pattern to simply break up user@domain into
different pieces that are easy to analyze. */

var matchArray=emailStr.match(emailPat);

if (matchArray==null) {

/* Too many/few @'s or something; basically, this address doesn't
even fit the general mould of a valid e-mail address. */

return false;
}
var user=matchArray[1];
var domain=matchArray[2];

// Start by checking that only basic ASCII characters are in the strings (0-127).

for (i=0; i<user.length; i++) {
if (user.charCodeAt(i)>127) {
return false;
   }
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {
return false;
   }
}

// See if "user" is valid 

if (user.match(userPat)==null) {

// user is not valid

return false;
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
host name) make sure the IP address is valid. */

var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {

// this is an IP address

for (var i=1;i<=4;i++) {
if (IPArray[i]>255) {
return false;
   }
}
return true;
}

// Domain is symbolic name.  Check if it's valid.
 
var atomPat=new RegExp("^" + atom + "$");
var domArr=domain.split(".");
var len=domArr.length;
for (i=0;i<len;i++) {
if (domArr[i].search(atomPat)==-1) {
return false;
   }
}

// Make sure there's a host name preceding the domain.

if (len<2) {
return false;
}

// If we've gotten this far, everything's valid!
return true;
}
