/**
 * alex.nguyen@wk.com
 */
 
//Main namespace
var edun = {
	nav: {},
	utils: {},
	globals: {},
	gui: {}
};

edun.utils.renderFonts = function() {
	Cufon.replace($('.letterGothicStd'), { fontFamily: 'Letter Gothic Std', hover: {color: '#0ff'}, hoverables: {li:'true', a:'true'} });

	// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
	// Homepage Flash
	// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	
	function startAltContent(){
		var navWidth = 188;
		if ((screen.width>360)) {
			startSlideshow();
		} else  {
			$("body").css({"width":screen.width+"px","max-width":screen.width+"px"})	
			var leftAmount = 20;
			$("#nav").css({"left":leftAmount+"px"})
			$("#flashcontent").append($("<img class='homepage_img' id='homepage_img_1' src='library/images/edun/homepage_bgs/mobile_bg.jpg' />"));
		}
	}

	var currentImageNum = 1;
	function startSlideshow(){
		$("#flashcontent").append($("<img class='homepage_img' id='homepage_img_1' src='/images/homepage/photo_1.jpg' />"));
		$("#flashcontent").append($("<img class='homepage_img' id='homepage_img_2' src='/images/homepage/photo_2.jpg' />"));
		$("#flashcontent").append($("<img class='homepage_img' id='homepage_img_3' src='/images/homepage/photo_3.jpg' />"));
		$("#flashcontent").append($("<img class='homepage_img' id='homepage_img_4' src='/images/homepage/photo_4.jpg' />"));
		var imageRatio = 1024/768;
		var windowRatio = $(window).width() / $(window).height();
		if(imageRatio > windowRatio){
			$(".homepage_img").css("height","100%");
			$("#flashcontent").css("overflow-x","hidden");
		}else{
			$(".homepage_img").css("width","100%");
		}
		if($(window).width() >= $(window).height()){
		}else{
		}
		$(".homepage_img").css("cursor","pointer");
		$(".homepage_img").css("display","none");
		$(".homepage_img").css("position","absolute");
		$(".homepage_img").css("top","0px");
		$(".homepage_img").css("z-depth","5");
		$("#homepage_img_1").css("display","block");
		$(".homepage_img").click(function(){
			showImage(currentImageNum + 1);
			return false;
		});
	}

	function showImage (num) {
		if(num == 5) num = 1;
		var previousImageNum = num - 1;
		if(previousImageNum == 0) previousImageNum = 4;
		$("#homepage_img_"+num).css("z-depth","10");
		$("#homepage_img_"+previousImageNum).css("z-depth","5");
		$("#homepage_img_"+num).fadeIn(400, function(){
			$("#homepage_img_"+previousImageNum).css("display","none");
		});
		currentImageNum = num;
	}

	
	setTimeout(function(){
		if(window.location.pathname == "/"){
			$(document).ready(function(){
				$('#container').css({'width':'100%','height':'100%'});
				if ($('#flashcontent').flash) {
					$('#flashcontent').flash({
						src: '/swf/edun.swf',
						width: "100%",
						height: "100%",
						wmode: "opaque"
					}, {
						version: 10
					}, null, function(){
						startAltContent();
					});
				}else{
					startAltContent();
				}
			});
			

		  	//flash tracking
			function trackFlashEvent(eventAction, eventLabel){
				_gaq.push(['_trackEvent', 'flash_homepage', eventAction, eventLabel]);
			}
		}
	});
}


edun.utils.preload = function() {
	
    spinner("landing-load", 5, 10, 12, 2, "#fff");
	$(function () {
        var img = new Image();
		var allimg = $('#landing-right img');
		allimg.hide();
		
		allimg.each(function(){
			var src = $(this).attr('src');
			$(this).load(function () {
		            //$(this).css('display', 'none'); // .hide() doesn't work in Safari when the element isn't on the DOM already
		            $(this).hide();
		            $('#landing-load').remove();
		            $(this).fadeIn();
		        }).error(function () {
		            // notify the user that the image could not be loaded
		        }).attr('src', src);
	    	});
		});
        
}

edun.utils.zoom = function() {
	var cur_color = main_id;

	$('[id*=-more-views]').hide();
	$('#'+cur_color+'-more-views').show();
	$("div.main-image").hide();
	$("."+cur_color+":first").show();

    $('#product-current-color').html('Color / '+cur_color.replace("-"," "));	
	var lastView = cur_color+'_front_zoom';
	

	$('a.color-swatch').mouseover(function(){
		
		cur_color = $(this).attr('id');
		
		$('#product-current-color').html('Color / '+cur_color.replace("-"," "));
		$(".main-image").find('img').css('top',0);
		$(".main-image").find('img').css('left',0);
		$(".main-image").find('img').css('width','auto');
		$(".main-image").find('img').css('height','100%');
		

		$('[id*=-more-views]').hide();
		$('#'+cur_color+'-more-views').show();
		$("div.main-image").hide();
		$("."+cur_color+":first").show();
		

		$.panzoom('div.main-image:visible', zoomImgs[cur_color+"_front_zoom"]);
		
	});

	
	
	//get data from view links to switch array based on link
	$('.image-link').click(function(){


		// build the text for the array index gnenerated for product view zooms
    this.lastView = $(this).html()+'_zoom';
	this.lastView = this.lastView.replace(' ', '_');
	this.lastView = this.lastView.toLowerCase();
	this.lastView = cur_color+'_'+this.lastView;
	
	
	var id = $(this).attr('id');
	$("div.main-image").hide();
	$("div#"+id+"-image").show();

	
	$(".main-image").find('img').css('top',0);
	$(".main-image").find('img').css('left',0);
	$(".main-image").find('img').css('width','auto');
	$(".main-image").find('img').css('height','100%');
	// pass large file url as argument to zoom function
	$.panzoom('div.main-image:visible', zoomImgs[this.lastView]);

	});
		
		

	
	$.panzoom('div.main-image:visible', zoomImgs[lastView]);



	
}




edun.utils.flyout = function() {
	
	
$('.products_flyout').hide();


// add hide window function to the close button
$('.products_flyout > .products_close_button, .added_product > .products_close_button').click(function(){
	$(this).parent().fadeOut();
	$("#blackback").fadeOut(function() {$("#blackback").remove()});
	});


// any div with class flyout that has an a tag with an id = x will open a corresponding div with that class x.  
// adding 'blockout' to the div class will instantiate a darkened transparent background. 
$('div.p_flyout > a:first-child').click(function(){
	var win = "div."+$(this).attr('id');
	win = $(win);
	win.fadeIn(400);

	if(win.hasClass('blockout')) {
	$('body').prepend('<div id="blackback">&nbsp;</div>');
	$("#blackback").fadeIn(400);
	win.css('z-index', 7);
	$("#blackback").click(function(){
			win.fadeOut(400);
			$("#blackback").fadeOut(function() {$("#blackback").remove()});
	});
	}
  return false;
	
	
});

/*
$('body').click(function(){

       win.fadeOut();
		$("#blackback").fadeOut(function() {$("#blackback").remove()});
	
	});
*/
	
}

edun.utils.captcha = function() {
	var countries = new Array("uganda", "kenya", "lesotho", "madagascar", "tanzania");
	var test = countries[Math.floor(Math.random() * countries.length)];
	$("#contact_cap_display").html(test);
	$("#jobcaptcha div.job_error").hide();
	$("#eduncaptcha").blur(function(){
		if($('#eduncaptcha').val().toLowerCase() != test){
			$("#jobcaptcha div.job_error").show();
			$("input.submitbtn").click(function(){
				return false;
			});
			$('#jobcaptcha div.job_input_cap').addClass('job_input_error');
		}
		else{
			$("input.submitbtn").unbind('click');	
			$('#jobcaptcha div.job_input_cap').removeClass('job_input_error');
			$("#jobcaptcha div.job_error").hide();
		}
	});
	
	$("input.submitbtn").click(function(){

		if($('#eduncaptcha').val().toLowerCase() != test){

			$("#jobcaptcha div.job_error").show();
			$('#jobcaptcha div.job_input_cap').addClass('job_input_error');
			return false;
		}
		else{
			$("input.submitbtn").unbind('click');	
			$('#jobcaptcha div.job_input_cap').removeClass('job_input_error');
			$("#jobcaptcha div.job_error").hide();
		}
	});
}

edun.utils.followUs = {
	timer : {},
	initialize : function() {
		$("#follow-us-link").mouseenter(function() { 
			clearTimeout(edun.utils.timer);
			$("#footer-follow-us").css({top: ($('#footer').offset()['top']-28)+'px'}).fadeIn(300);
			$("#footer-follow-us").css({left: ($('#footer').offset()['left']+10)+'px'}).fadeIn(300);
		});
		$("#footer-follow-us").mouseenter(function(){
			clearTimeout(edun.utils.timer);
		});
		$("#follow-us-link").mouseleave(function() { 
			edun.utils.timer = setTimeout(edun.utils.followUs.hide, 1500);
		});
		$("#footer-follow-us").mouseleave(function() {
			edun.utils.timer = setTimeout(edun.utils.followUs.hide, 1500);
		});
	},
	hide : function() {
		$("#footer-follow-us").fadeOut(300);
	}
};

edun.nav = {
	activeGender : "",
	timer : false,
	shopMouseOver : function() {
		$('#shop>a').unbind();
		$('#women').animate({ height:"show" }, 400);
		$('#men').animate({ height:"show" }, 400);
		$('#features').animate({ height:"show" }, 400);
	},
	collectionMouseOver : function() {
		$('#collectionLookbook').animate({ height:"show" }, 150);
	},
	missionMouseOver : function() {

	},
	initialize : function() {
		if(jQuery.browser.webkit){
			$('#collection').css({
				'padding-top':'0px',
				'height':'20px'
			});
		}
		if(window.location.pathname.indexOf('shop') > -1 || window.location.pathname.indexOf('products') > -1) {
			setTimeout(function(){
				$('#women').animate({ height:"show" }, 400);
				$('#men').animate({ height:"show" }, 400);
				$('#features').animate({ height:"show" }, 400);
			}, 1000);
			$('#collection>a').bind('mouseover', edun.nav.collectionMouseOver);
		}else{
			$('#shop>a').bind('mouseover', edun.nav.shopMouseOver);
			$('#collection>a').bind('mouseover', edun.nav.collectionMouseOver);
			$('#nav').mouseenter(function(){
				edun.nav.mouseIsInside = true;
				clearTimeout(edun.nav.navTimeout);
			});
			$('#nav').mouseleave(function(){
				edun.nav.mouseIsInside = false;
				clearTimeout(edun.nav.navTimeout);
				edun.nav.navTimeout = setTimeout(edun.nav.leaveTimer, 1250);
			});
		}
		$('#nav').fadeIn(400);
	},
	mouseIsInside : false,
	navTimeout : {},
	leaveTimer : function() {
		if(!edun.nav.mouseIsInside){
			edun.nav.activeGender = "";
			edun.nav.removeListener($('#women').find('a')[0]);
			edun.nav.removeListener($('#men').find('a')[0]);
			$(".gender").animate({ height:"hide" }, 400);
			$('#shop').find('a').bind('mouseover', edun.nav.shopMouseOver);
		}else{
			//should never get called.
		}
	},
	activeGender : "",
	addListener : function(element) {
		$(element).mouseover(function(){
			edun.nav.removeListener(element);
			edun.nav.activeGender = $(element).parent().attr('id');
			if(edun.nav.activeGender == 'women'){
				$('#women').find('ul').animate({ height:"show" }, 400);
				if($('#men').find('ul').css('display') == 'block'){
					$('#men').find('ul').animate({ height:"hide" }, 400);
					edun.nav.addListener($('#men').find('a')[0]);
				}
			}else{
				$('#men').find('ul').animate({ height:"show" }, 400);

				if ($('#women').find('ul').css('display') == 'block') {
					$('#women').find('ul').animate({ height: "hide" }, 400);
					edun.nav.addListener($('#women').find('a')[0]);
				}
			}
		});
	},
	removeListener : function(element) {
		$(element).unbind();
	}
};

/**
 * Checks for the existence of the global console object and the log method.
 * Should be used instead of console.log so that IE doesn't throw errors when
 * it doesn't find console.
 * @param {Object} message - Message to be sent to console.log
 */
edun.utils.log = function(message) {
	try{
		console.log(message);
	}catch(err){
		return false;
	}
}


/////////////////////////////////////////////////////////////////////////////////////////
function init() {
	edun.utils.renderFonts();
	edun.nav.initialize();
	edun.utils.center();

	setTimeout(function(){	
		$('#nav').fadeIn(400);
		$('#footer').show();
		edun.utils.footer();

		}, 500);
		

	//edun.utils.captcha();
	//edun.utils.flyout();
}

function addCategoryHover(action, taxon) {

/*
	*hack for IE7.  can't dynamically calculate top/height css offsets
*/
if(navigator.userAgent.indexOf('MSIE 7.0') > -1) {
	$('.grid-overlay').css('visibility', 'hidden');
	$('.overlay-large').css({
		'top' : '-483px',
		'height' : '483px'
	});
	$('.overlay-large').css({
		'top' : '-483px',
		'height' : '483px'
	});
	$('.overlay-medium').css({
		'top' : '-244px',
		'height' : '244'
	});
	$('.overlay-small').css({
		'top' : '-245px',
		'height' : '245px'
	});
	$('.hover-large').css('top', '-966px');
	$('.hover-medium').css('top', '-488px');
	$('.hover-small').css('top', '-490px');
}    
    $('#cross-sell').show();

	var imgdiv = new Array('#landing_img_hover','#landing_img_hover2');
	var coin = 0;


	$('.category-hover, .product-cell').each(function(){
		$('#'+$(this).attr('id')+'-overlay').animate({'opacity':0.3}, 0);
		$('#'+$(this).attr('id')+'-hover').animate({'opacity':0}, 0);
	});
	
	
  $('.category-hover, .product-cell').each(function(){	
    $(this).mouseover(function(){
      $('#'+$(this).attr('id')+'-overlay').stop(true, true);
	  $('#'+$(this).attr('id')+'-hover').stop(true, true);
      $('#'+$(this).attr('id')+'-overlay').animate({'opacity':0}, 400); 
      $('#'+$(this).attr('id')+'-hover').animate({'opacity':1}, 400); 
    }).mouseleave(function(){
      $('#'+$(this).attr('id')+'-overlay').animate({'opacity':0.3}, 400); 
      $('#'+$(this).attr('id')+'-hover').animate({'opacity':0}, 400); 
    }).click(function(){
      if(action=='products') {
        document.location = "/"+action+"/"+$('#'+$(this).attr('id')+'-link-holder').val()+"?color="+$(this).attr('id')+"&cat="+taxon;
      }else{
		document.location = "/shop/"+action+"/"+$(this).attr('id');
	  }
    });
  });



	var enter_cell_flag = 0;


 // landing left image change
  $(".product-cell").each(function() {
	var el = $(this);
		$(this).mouseenter(function(){	
			enter_cell_flag = 1;
			$('#landing_img_default').fadeOut('slow');
			$('#cross-sell').fadeOut(200);
		    $(imgdiv[coin]).stop(true,true);
		    $(imgdiv[coin]).fadeOut('slow');
		    coin = (coin + 1) % 2;
		    $(imgdiv[coin]).stop(true,true);
			$(imgdiv[coin]).attr('src', el.find('.landing_rollover:first').attr('rel'));
		    $(imgdiv[coin]).fadeIn('fast');

		});
		
		$(this).mouseleave(function(){	
			landing_reset();
		});
  });

  $(".landing_rollover").each(function() {
		var el = $(this);
	  $(this).mouseenter(function(){
	  $(imgdiv[coin]).stop(true,true);
	  $(imgdiv[coin]).fadeOut('slow');
	  coin = (coin + 1) % 2;
	  $(imgdiv[coin]).stop(true,true);
	  $(imgdiv[coin]).attr('src', $(this).attr('rel'));
	  $(imgdiv[coin]).fadeIn('fast');
	  });
  });


function landing_reset(){
	
	enter_cell_flag = 0;
	

	setTimeout( function(){
		if(enter_cell_flag == 0) {
			$('#landing_img_default').fadeIn('fast');
		    $(imgdiv[0]).fadeOut('slow');
		    $(imgdiv[1]).fadeOut('slow');
			$('#cross-sell').fadeIn("slow");	
		}			
		}, 500);
}



}
                                     
$(document).ready(function(){
	init();
	edun.utils.followUs.initialize();
  $.get(document.location.protocol+"//"+document.location.host+"/home/order_info", function(data) {
    $('#utils').append(data);
	  Cufon.replace($('.letterGothicStd'), { fontFamily: 'Letter Gothic Std' });
    Cufon.now();
  });
	$(window).resize(function() {
			edun.utils.center();
			edun.utils.footer();
	});
	
  $(".also_like_img div").each(function() { $(this).css('opacity', 0.15); });
  $(".also_like_img").each(function() { 
    $(this).mouseenter(function() {$(this).find('div').css('opacity', 0)}).mouseleave(function() {$(this).find('div').css('opacity', 0.15)}); 
  });

	// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
	// Google Analytics
	// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
	/*
	var _gaq = _gaq || [];
	_gaq.push(['_setAccount', 'UA-1852748-7']);
	_gaq.push(['_trackPageview']);

	(function() {
	  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
	  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
	})();
	*/

});

edun.utils.center = function() {
	var loc = window.location;
	loc = loc.toString();               
	var center = ( $(window).height() - $("#container").height() ) / 2;
	var isProduct = loc.indexOf("products");
	if(center > 0 && isProduct < 0) {
		$("#container").css('margin-top', center);
	}
}

jQuery.fn.exists = function(){return jQuery(this).length>0;}

edun.utils.footer = function() {
	// dynamically bottom align footer     
	if(window.location.pathname != "/"){
		$('#footer').css('top', 0);
		var dif = $(window).height() - $('#footer').offset()['top'] -14;
		if (dif < 5){
			dif = 5;
		}
		$('#footer').css('top', dif+'px');
	}else{    
    $('#footer').css({"position":"absolute","bottom":"5px"});
    if(!$('.footerBg').exists()) {
      var bg = $('<div class="footerBg"></div>');      
      $('body').append(bg);         
    } 
    setTimeout(function(){
      $('.footerBg').fadeIn(400);
    },1500);
    $('.footerBg').css({top: ($(document).height()-16)+"px"});
	}
}

// rafael svg lib
function spinner(holderid, R1, R2, count, stroke_width, colour) {
    var sectorsCount = count || 12,
        color = colour || "#fff",
        width = stroke_width || 15,
        r1 = Math.min(R1, R2) || 35,
        r2 = Math.max(R1, R2) || 60,
        cx = r2 + width,
        cy = r2 + width,
        r = Raphael(holderid, r2 * 2 + width * 2, r2 * 2 + width * 2),
        
        sectors = [],
        opacity = [],
        beta = 2 * Math.PI / sectorsCount,

        pathParams = {stroke: color, "stroke-width": width, "stroke-linecap": "round"};
        Raphael.getColor.reset();
    for (var i = 0; i < sectorsCount; i++) {
        var alpha = beta * i - Math.PI / 2,
            cos = Math.cos(alpha),
            sin = Math.sin(alpha);
        opacity[i] = 1 / sectorsCount * i;
        sectors[i] = r.path([["M", cx + r1 * cos, cy + r1 * sin], ["L", cx + r2 * cos, cy + r2 * sin]]).attr(pathParams);
        if (color == "rainbow") {
            sectors[i].attr("stroke", Raphael.getColor());
        }
    }
    var tick;
    (function ticker() {
        opacity.unshift(opacity.pop());
        for (var i = 0; i < sectorsCount; i++) {
            sectors[i].attr("opacity", opacity[i]);
        }
        r.safari();
        tick = setTimeout(ticker, 1000 / sectorsCount);
    })();
    return function () {
        clearTimeout(tick);
        r.remove();
    };
}