/**
 * @author neila
 */
$(document).ready(function() {
	/* Round corners 
	$('#nav li.level1').corner("notch 2px");
	$('p.shop_button').corner('');
	*/
		
	/* IE6 Transparancies */
	if(browser_is_ie6()) {
		//$('#content, #panoramic_background, #my_tools, #special_offers_div, #download_pdf').supersleight();
		$('#featured_products_div, #bestsellers_div, #products_wrap, #cart_item_wrap, #my_tools, #special_offers_div, #download_pdf').supersleight();
	}
	
	/* Search box */
	if($('#search_query').val() == ''){
		$('#search_query').val('Search our Shop');
	}
	
	$('#search_query').focus(function() {
		if($(this).val() == 'Search our Shop')
			$(this).val('');	
	});
	
	$('#search_query').blur(function() {
		if($(this).val() == '')
			$(this).val('Search our Shop');
	});
	
	/* header login */
	$('#header_username').val('your@email.com');
	$('#header_password').val('password');
	
	$('#header_username').focus(function() {
		if($(this).val() == 'your@email.com')
			$(this).val('');	
	});
	
	$('#header_username').blur(function() {
		if($(this).val() == '')
			$(this).val('your@email.com');
	});
	
	$('#header_password').focus(function() {
		if($(this).val() == 'password')
			$(this).val('');
	});
	
	$('#header_password').blur(function() {
		if($(this).val() == '')
			$(this).val('password');
	});
	
	$('body').addClass('js_enabled');
	
	/* Footer links shade layer handler */
	$('li.footer_link a.content').bind('click keyup',function(e) {
		
		e.preventDefault();
		
		content_id = $(this).attr('class').split(' ').pop();
		link_ref = '?page=content&amp;id=' + content_id;
		 
		shade_layer('content','744','496','B3B7BD',link_ref,'','');
	});
	
	initOverLabels();
	
	// Flash Banner
	flashVars = {};
	flashVars.clickTag = 'http://www.channel4learning.com/support/whatsnew/index.html';
	
	flashParam = {};
	
	flashAttr = {};
	
	/*swfobject.embedSWF(
		'http://www.channel4learning.com/support/global/header/banner/C4L_V4.swf',
		'header_flash_banner',
		'468',
		'60',
		'7',
		null,
		flashVars,
		flashParam,
		flashAttr
	);*/

    var miniSignUpPlaceHolder = $('#mini-signup-email').val();

    $('#mini-signup-email')
        .focus(function(event){
            if(miniSignUpPlaceHolder == $(this).val()) {
                $(this).val('');
                $(this).toggleClass('place-holder');
            }
        })
        .blur(function(event){
            if('' == $(this).val()) {
                $('#mini-signup-email').val(miniSignUpPlaceHolder);
                $(this).toggleClass('place-holder');
            }
        });

    $('#mini-signup-form').submit(function(event) {
        var value = $('#mini-signup-email').val();
        if('' == value || miniSignUpPlaceHolder == value) {
            event.preventDefault();
        }
    });
});

function check_account(source)
{
	if(source.val().length > 5 && $("#email_login_prompt").attr('id')) {
	
		$.get("ajax/",{
		"page":"login",
	 	"action": "check_account",
	 	"email": source.val()
	 	},
	 	function(response) {
			
			if(response == 1) {
				
				$("#email_login_prompt").show();
				
				href = $("#email_login_prompt a.login").attr("href");
				
				if(!href){
					return;
				}
				
				split_href = href.split("&");
				
				if(source.attr("id") == "email") {
					redirect="my_account";
				}
				else if(source.attr("id") == "p_email") {
					redirect = "checkout";
				}
				
				if(split_href[1]){
					split_href[1] = "redirect=" + redirect;
				}
				
				href = split_href.join("&");
				
				$("#email_login_prompt a.login").attr("href",href);

				$('#cart_continue input').attr("disabled","disabled");
			}
			else {

				$("#email_login_prompt").hide();
				$('#cart_continue input').removeAttr("disabled");
			}
		});
	}
	else {
		$("#email_login_prompt").hide();
		$('#cart_continue input').removeAttr("disabled");		
	}
}
function send_new_password(email) {

	$.get("ajax/index.php",{
 		"page": "login",
		"action":"lost_password",
 		"email": email
 	},
	function(response) {
		
		if(response == 1) {
			$("#email_login_prompt").html(
				"<p>A new password has been sent to your email address</p>"+
				"<p>You may now <a href=\"?page=login&redirect=checkout\">Login</a> with your new password</p>"
			);	
		}
	});
}
/* IE6 fix for suckerfish menu */
//sfHover = function() {
//	var sfEls = document.getElementById("nav").getElementsByTagName("LI");
//	for (var i=0; i<sfEls.length; i++) {
//		sfEls[i].onmouseover=function() {
//			this.className+=" sfhover";
//		}
//		sfEls[i].onmouseout=function() {
//			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
//		}
//	}
//}
//if (window.attachEvent) window.attachEvent("onload", sfHover);

/*
	Style active nodes for suckerfish
*/
function style_menu(category_id) {
	
	source = $("#node_" + category_id);
	source.addClass('selected');
	source.parents('li').addClass('selected');
}

function browser_is_ie6() {
	
	if(typeof document.body.style.maxHeight === "undefined") {
	        return true;
	} else {
	        return false;
	}
}

function initOverLabels () {
  if (!document.getElementById) return;      

  var labels, id, field;

  // Set focus and blur handlers to hide and show 
  // labels with 'overlabel' class names.
  labels = document.getElementsByTagName('label');
  for (var i = 0; i < labels.length; i++) {

    if (labels[i].className == 'overlabel') {

      // Skip labels that do not have a named association
      // with another field.
      id = labels[i].htmlFor || labels[i].getAttribute('for');
      if (!id || !(field = document.getElementById(id))) {
        continue;
      } 

      // Change the applied class to hover the label 
      // over the form field.
      labels[i].className = 'overlabel-apply';

      // Hide any fields having an initial value.
      if (field.value !== '') {
        hideLabel(field.getAttribute('id'), true);
      }

      // Set handlers to show and hide labels.
      field.onfocus = function () {
        hideLabel(this.getAttribute('id'), true);
      };
      field.onblur = function () {
        if (this.value === '') {
          hideLabel(this.getAttribute('id'), false);
        }
      };

      // Handle clicks to label elements (for Safari).
      labels[i].onclick = function () {
        var id, field;
        id = this.getAttribute('for');
        if (id && (field = document.getElementById(id))) {
          field.focus();
        }
      };

    }
  }
};

function hideLabel (field_id, hide) {
  var field_for;
  var labels = document.getElementsByTagName('label');
  for (var i = 0; i < labels.length; i++) {
    field_for = labels[i].htmlFor || labels[i].getAttribute('for');
    if (field_for == field_id) {
      labels[i].style.textIndent = (hide) ? '-1000px' : '0px';
      return true;
    }
  }
}

(function($){
$.fn.extend({
	emailExists : function(options) {
        if(typeof options == 'undefined') {
            options = {};
        }

        options = $.extend({}, $.EmailExists.options, options);

		return this.each(function(){
			new $.EmailExists(this, options);
		});
	}
});

/**
 * See if email exists
 */
$.EmailExists = function(input, options) {
	var KEY = $.EmailExists.constants.KEY;
	var cache = [];
	var $input = $(input);
	var $form = $($input.parents('form'));
    var ajax = null;

	if(false === $form.find('.email-exists').hasClass('show_me')) {
		$form.find('.email-exists')
			 .removeClass('hide_me')
			 .hide();
	}

	$form.find('.ajax-loading')
	     .removeClass('hide_me')
		 .hide();

	$input.bind('keyup', {}, function(event){
		//	ignore certain keys
		if(
			KEY.TAB 		== event.keyCode
			|| KEY.ENTER 	== event.keyCode
			|| KEY.LEFT 	== event.keyCode
			|| KEY.UP 		== event.keyCode
			|| KEY.RIGHT 	== event.keyCode
			|| KEY.DOWN 	== event.keyCode
			|| KEY.PAGEUP 	== event.keyCode
			|| KEY.PAGEDOWN == event.keyCode
			|| KEY.ESC 		== event.keyCode
			|| KEY.ENTER	== event.keyCode
			|| KEY.RETURN 	== event.keyCode
			|| KEY.CTRL 	== event.keyCode
			|| KEY.SHIFT 	== event.keyCode
		) {
			return null;
		}

		var $input = $(this);
		var $message = $($input.parents('.input-wrap')
							   .find('.email-exists'));

		// See if this email has been found already
		var cacheLength = cache.length;
		for(var i = 0; i < cacheLength; i++) {
			if($input.val() == cache[i]) {
				$message.slideDown();
				return null;
			}
		}

		//	If the email is too short, don't bother requesting
		if(5 > $input.val().length) {
			$message.slideUp();
			return null;
		}

        if(ajax !== null) {
            ajax.abort();
        }
        
		ajax = $.ajax({
			type : 'post'
			,url : 'ajax/index.php?page=signup&action=validate_email'
			,dataType : 'text'
			,data : {
				email : $input.val()
			}
			,beforeSend : function(xmlRequest) {
				$input.siblings('.ajax-loading').fadeIn();
			}
			,success : function(data) {

				if(0 == data) {
					cache.push($input.val());
					$message.slideDown();
				}
				else if(1 == data){
					$message.slideUp();
				}
			}
			,complete : function(xmlRequest, status){
				$input.siblings('.ajax-loading').fadeOut();
			}
		});
	});

};

$.EmailExists.constants = {
	KEY : {
		LEFT: 37,
		UP: 38,
		RIGHT: 39,
		DOWN: 40,
		DEL: 46,
		TAB: 9,
		CTRL: 17,
		RETURN: 13,
		ENTER: 23,
		SHIFT: 26,
		ESC: 27,
		COMMA: 188,
		PAGEUP: 33,
		PAGEDOWN: 34,
		BACKSPACE: 8
	}
};

$.EmailExists.options = {
    
};

})(jQuery);
