//////////////////////////////////////////////////////
//
// The purpose of this file is to
// apply a hover class on mouseover
// on the <li> elements in the nav.
// This is because IE doesn't put
// the pseudo class :hover on <li> elements
//
// This is code that uses the
// jquery javascript library (http://jquery.com/)
//
//////////////////////////////////////////////////////

function validEmail(e)
{
	if (/^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[a-z]{2,4}|museum|travel)$/i.test(e)){
		return true;
	}
	return false;
}
function submitForm()
{
	if( $("#ContactFirstName")[0].value == '')
	{
		alert('Please enter your first name');
		return false;
	}
	if( $("#ContactLastName")[0].value == '')
	{
		alert('Please enter your last name');
		return false;
	}
	if( !validEmail($("#ContactEmail")[0].value) )
	{
		alert('Please enter a valid email address');
		return false;
	}
	
	document.forms[0].submit();
	return false;
} 

var images = new Array();
images.push('<img src="cmsimages/text-take_the_first_step.gif" alt="Take the first step" />');
images.push('<img src="cmsimages/text-let_us_aid.gif" alt="let us aid your success" />');
images.push('<img src="cmsimages/text-drop_by_open_house.gif" alt="drop by our open house" />');
images.push('<img src="cmsimages/text-contact_us.gif" alt="contact us" />');

var texts = new Array();
texts.push("<br/>Start the journey. Please complete the form and select \"submit\", or call us at 212-367-0346.<br/> We'll contact you promptly with all the information you need to begin the Aveda adventure. ");
texts.push("<br/>Please complete the form and select \"submit\", or call us at 212-367-0346.<br/> We will contact you promptly with information about our financial assistance programs.");
texts.push("<br/>Please complete the form and select \"submit\", or call us at 212-367-0346.<br/> We'll be in touch shortly with information about this month's open house schedule.");
texts.push("<br/>Start the journey. Please complete the form and select \"submit\", or call us at 212-367-0346.<br/> We'll contact you promptly with all the information you need to begin the Aveda adventure.");

// return value from key in URL query string
function getQueryKey(searchKey) {
    var url = location.href;
    var query = url.split("?");
    if(query.length < 2)
        return "";
    var pairs = query[1].split("&");
    
    var split, key, val, found = false;
    
    for ( var i = 0; i < pairs.length; i++ ) {
        split = pairs[i].split("=");
        key = split[0];
        val = split[1];
        
        if ( key == searchKey ) {
            found = val;
            return found;
        }
    }
    
    if ( found == false ) {
        return "";
    }
}

function IsNumeric(strString)
// check for valid numeric strings
{
    var strValidChars = "0123456789.-";
    var strChar;
    var blnResult = true;
    
    if (strString.length == 0) return false;
    
// test strString consists of valid characters listed above
    for (i = 0; i < strString.length && blnResult == true; i++) {
        strChar = strString.charAt(i);
        if (strValidChars.indexOf(strChar) == -1) {
            blnResult = false;
        }
    }
    return blnResult;
}
jQuery.extend({
// The opposiite of jQuery's native $.param() method. Deserialises aparam string to an object:
// Note: TODO: Allow for multiple params with same name (to become anarray attribute).
	unparam : function(params){
		var objResult = {};
		if(params == undefined || params == '')
			return objResult;
		$.each(params.split("&"), function(){ var prm=this.split("=");
			objResult[prm[0]] = prm[1]; });
			return objResult;
	}
}); 
function in_array(needle, haystack, argStrict) {
	var key = '', strict = !!argStrict;
	if (strict) {
		for (key in haystack) {
			if (haystack[key] === needle) {
				return true;
			}
		}
	} else {
		for (key in haystack) {
			if (haystack[key] == needle) {
				return true;
			}
		}
	}
	return false;
}
function getGoogleUtms()
{
	var utm = {source: '', medium: '', term: '', content: '', campaign: ''};
	var url = location.search;
	var query = url.split("?");
	if(query.length < 2)
		return utm;
	var getAsObject = $.unparam(query[1]);
	for(var i = 0; i < utmKeys.length; i++)
	{
		key = 'utm_' + utmKeys[i];
		if(getAsObject[key] != undefined)
			utm[utmKeys[i]] = getAsObject[key];
	}
	return utm;
};
var utmKeys = new Array('medium','term','content','campaign','source');
var COOKIE_NAME = 'myutms';
var options = { path: '/', expires: 1 };
//check and set google utm cookie
$(document).ready(function(){
	var utm = getGoogleUtms();
	if(utm.source != '' && utm.medium != '' && utm.name != '')
	{
		$.cookie(COOKIE_NAME, $.param(utm), options);
	}
});
//get google utm cookie and set as hidden fields in form
$(document).ready(function(){
	var moreInfoForm = $('#moreInfoForm');
	if(moreInfoForm.length > 0){
		var billy = $.cookie(COOKIE_NAME);
		var utm = $.unparam($.cookie(COOKIE_NAME));
		//var utm = {source: 'source value', medium: 'medium value', term: 'term value', content: 'content value', campaign: 'campaign value'};
		for(var p in utm)
		{
			if (!(utm[p] instanceof Function)) {
				val = unescape(utm[p]);
				val = val.replace(/\+/g, " ");
				val = val.replace(/\%20/g, " ");
				moreInfoForm.append('<input type="hidden" name="data[Utm][' + p + ']" value="'+ val + '"');
			}
		}
	}
});



$(window).load(function() {
    
    /*$("#images a img").each(function() {
        this.src = 'cmsimages/' + this.id + Math.floor(3*Math.random()) + '.gif';
    });*/
    if($('#images p').length > 0)
	{
		p = $('#images p')[Math.floor($('#images p').length * Math.random())];
        $(p).css('display', 'block');
	}
    
//Jfeed
   /* if($(".blogFeed").length > 0) {
        jQuery.getFeed({
            url: 'blog/?feed=rss2',
                    dataType: ($.browser.msie) ? "text" : "xml",
                            success: function(feed) {
                        var length = feed.items.length;
                        var theHTML = "<ul>";
                        for(var x = 0; x < length; x++ ) {
                            theHTML = theHTML + '<li><h2><a href="' + feed.items[x].link + '">' + feed.items[x].title + '</a></h2>' + feed.items[x].description + '</li>'
                                    var bob = feed.items[x];
                        }
                        theHTML = theHTML + '</ul>';
                        if($('.blogFeed').length > 0)
                            $('.blogFeed')[0].innerHTML = theHTML;
                        
                    }
        });
    }*/
    
    
// Bind default text action to the following elements
    $(".emptytext").focus( function(){
        if ( $(this).val() == $(this)[0].defaultValue ) {
            $(this).val("");
        }
    });
    $(".emptytext").blur( function(){
        if ( $(this).val() == "" ) {
            $(this).val( $(this)[0].defaultValue );
        }
    });
    
    $("#page.more_info").each(function(){
        var myQuery = getQueryKey('say');
        var msg = 0;
		if($("#rot_img").length == 0)
			return;
        if(myQuery != '') {
            msg = decodeURIComponent(myQuery);
            var index = parseInt(msg);
            if(index > 0 && index < images.length )
			{
                $("#rot_img")[0].innerHTML = images[msg];
				$("#rot_text")[0].innerHTML = texts[msg];
			}
            else
			{
                $("#rot_img")[0].innerHTML = images[0];
				 $("#rot_text")[0].innerHTML = texts[0];
			}
        } else {
            $("#rot_img")[0].innerHTML = images[0];
			 $("#rot_text")[0].innerHTML = texts[0];
        }
        //$('#moreInfoForm').append('<input type="hidden" name="page" value="' + msg + '"/>');
    });
    
     slideshow = $("#slideshow").each(function(){
        var anchors = $('#slideImage a',this);
        var images = $('#slideImage img',this);
        var text = new Array();
        var curr = 0;
       
        
        
		$('#textScreen')[0].innerHTML = '';
        for(var i = 0; i < anchors.length; i++) {
            var slideText = $('<div class="slideText"></div>').appendTo('#slideTextHolder');
            slideText.load(anchors[i].href + ' p', function(){
				$(this).find('a.internalLink').click(function(){
					href = this.href;
					index = href.substr(href.search(/#/) + 1,href.length - 1);
					changeSlide(parseInt(index) - 1);
					return false;
					//changeSlide()
				});
			});
            text.push(slideText);
        }
        
        var slideNav = $('<div id="slideNav"><ul></ul></div>').appendTo('#slideTextHolder');
        var ul = slideNav.children('ul');
        ul.append('<li class="prev"><a href="">&nbsp;</a></li>');
        for(var i = 0; i < images.length; i++) {
            ul.append('<li><a href="" id="a' + i + '">' + (i + 1) + '</a></li>');
        }
        ul.append('<li class="next"><a href="">&nbsp;</a></li>');
		
		var key = getQueryKey('slide');
		if(key != 'undefined' && IsNumeric(key))
		{
			if(key > 0 && key <= anchors.length)
				curr = key - 1;
				/*changeSlide(key - 1);*/
		}
        $(images[curr]).show();
        
        $(text).each(function(){
            $(this).fadeOut();
        });
        
        $(text[curr]).fadeIn();
        
        $('#imageScreen').fadeOut(2000);
        $('#textScreen').fadeOut(1000);
        
        $("#a" + curr).parent().addClass('selected');
		if(curr == 0)
			$('#slideNav li.prev a').addClass('inactive');
		else if(curr == anchors.length - 1)
			$('#slideNav li.next a').addClass('inactive');
		
		 
        
        function changeSlide(index) {
            
            
            if(index < 0 || index > anchors.length -1 )
                return false;
            if(index == 0) {
                $('#slideNav li.prev a').addClass('inactive');
                if(curr == anchors.length - 1)
                    $('#slideNav li.next a').removeClass('inactive');
            } else if(index == anchors.length - 1) {
                $('#slideNav li.next a').addClass('inactive');
                if(curr == 0)
                    $('#slideNav li.prev a').removeClass('inactive');
            } else if( curr == 0 && index != 0) {
                $('#slideNav li.prev a').removeClass('inactive');
            } else if( curr == anchors.length - 1 && index != anchors.length - 1) {
                $('#slideNav li.next a').removeClass('inactive');
            }
            var old = curr;
            curr = index;
//$("#msg").append('<p> old = ' + old + ' index =' + index + '</p>');
            $("#a" + old).parent().removeClass('selected');
            $("#a" + index).parent().addClass('selected');
            $('#imageScreen').fadeIn(20, function(){
                $(images[old]).hide();
                $(images[index]).show();
                $('#imageScreen').fadeOut(500);
            });
            $('#textScreen').fadeIn(20, function(){
                $(text[old]).hide();
                $(text[index]).show();
                $('#textScreen').fadeOut(500);
                
            });
        }
        
        $('#slideNav li a').click(function(){
            if(this.id != "") {
                var index = this.id.replace('a', '');
                changeSlide(index);
            }
            
            return false;
        });
        
        $('#slideNav li.prev a').click(function(){
            changeSlide(parseInt(curr) - 1);
        });
        
        $('#slideNav li.next a').click(function(){
            changeSlide(parseInt(curr) + 1);
        });
		
		
        
        
    });
    
    
    if (document.all&&document.getElementById) {
// this is needed for the IE 6 pseudo hover class bug
        $(".navtop > li").hover(function() {
            $(this).addClass("hover");
        },
                function() {
            $(this).removeClass("hover");
        });
        
        $(".navtop > li li ").hover(
                function() {
            $(this).addClass("hover");
        },
                function() {
            $(this).removeClass("hover");
            
        });
        
        
    } else {
// this is need for safari when nav covers flash
        $(".navtop li ul").mouseover(function() {
            $(this).addClass("redraw");
        });
        $(".navtop li ul").mouseout(function() {
            $(this).removeClass("redraw");
        });
    }
});

