$(document).ready(function() {

	browserCheck();
	tweakPager();
	cufonify();
	

//Initialize login popup
	$("a.loginLink").click(function() {
		$('#inline-1').modal();
	});

	$("#login-button").click(function() {
		$('#login-form').submit();
	});
	
	// Email subscribe
	$("#cta-newsletter form").submit( function() {
		$.ajax({
			url: "/mailinglist/subscribe",
			type: 'POST',
			data: "email=" +$("#cta-newsletter input[name=email]").val(),
			dataType: 'json',
			success: function(data){
				if(data.response == "OK"){
					$("#cta-newsletter").html('Thanks for signing up');
				}else{
					$("#cta-newsletter").html('There was an error.');
				}
				
			}
		});
		return false;
	});
	
	//$("#urlalias").keyup( function() {
	$("#ezcoa-401_alias").keyup( function() {
		var alias = $(this).val();
		if( alias.length >= 3 )
		{
		//	$("#urlalias-status").show();
			$.ajax({
				url: "/alias/availability/" + alias,
				type: 'GET',
				dataType: 'json',
				success: function(data){
					if(data.status == "ok"){
						$('#urlalias-status').attr('class','urlIsOK');
					}
					else{
						$('#urlalias-status').attr('class','urlIsBad');
					}
				}
			});
		}
	});
	
	// Cart bag count
	$.ajax({
	      url: "/shop/cart/cart/totalitems",
	      type: 'GET',
	      dataType: 'json',
	      success: function( data ){
			$("span.bag-count").prepend(data.total);
	      }
	 });

	// Search counts
	if( $("#searchResultsTotals" ) )
	{
		$.ajax({
			url: "/social/searchcount/" + $("#searchAgain input[name=SearchText]").val(),
			type: 'GET',
			dataType: 'json',
			success: function(data){
				$("span.designers").html(data.designers);
				$("span.styletrekkers").html(data.styletrekkers);
				$("span.looks").html(data.looks);
			}
		});
		
		$.ajax({
			url: "/shop/search/count/get/query/" + $("#searchAgain input[name=SearchText]").val(),
			type: 'GET',
			dataType: 'json',
			success: function(data){
				$("span.products").html(data.products);
			}
		});
	}
	
	//Cycle Home Page Masthead images
	$('.mast').cycle({
		fx: 'fade', 
		timeout: 5000,
		//next: '.mast-next',
		//prev: '.mast-prev',
		pause: 1
	});

	// Browse posttourl hooks
	$('select[name=vp_region]').change( function() {
		$(this).parent().submit();
	});
	
	$('select[name=vp_country]').change( function() {
		$(this).parent().submit();
	});

	//Handlers for deleting a look
	$('.delete_look').click(function(){
		$( this ).parent().submit();
		return false;
	});
	//Handlers for adding a new look
	$('#new_look_image').change(function(){
		var current_file = $( this ).attr('value');
		if ( current_file != '' )
		$('#submit_new_look').show();
	});

	//Handleers for the One-line status update
	$('#status-line-form-div').hide();

	$('#status-line-text').click(function(){
		current_status = $('#current-status').html();
		$('#status-form-text').attr("value", current_status);
		$( this ).hide();
		$('#status-line-form-div').show();
	});

	$('#submit-status-update').click(function(){
		//update status text in div if successful
		var new_status = $('#status-form-text').attr('value');

		//make call to /status/post
		callStatusPost( new_status );

		$('#status-line-form-div').hide();	
		$('#status-line-text').show();
	});

	//Handlers for the wall post
	
	//Handle cancel extras request
	$('.cancel-extras').click(function(){
		$('#wall-post-image').hide();
		$('#wall-post-video').hide();
		$('#wall-post-link').hide();
		$('#current-extra').attr('value', 'none');
		return false;
	});

	// Hide the extra fields
	$('#wall-post-image').hide();
	$('#wall-post-video').hide();
	$('#wall-post-link').hide();
	$('#current-extra').attr('value', 'none');

	//Switch to image extra
	$('#form-status li.image').click(function(){
		$('.wall-post').hide();
		$('#wall-post-image').show();
		$('#current-extra').attr('value', 'image');
		return false;
	});

	//Switch to link extra
	$('li.link').click(function(){
		$('.wall-post').hide();
		$('#wall-post-link').show();
		$('#current-extra').attr('value', 'link');
		return false;
	});

	//Switch to video extra
	$('li.video').click(function(){
		$('.wall-post').hide();
		$('#wall-post-video').show();
		$('#current-extra').attr('value', 'video');
		return false;
	});

	//Submit wall post
	$('#submit-wall-post').click(function(){
		var current_extra = $('#current-extra').attr('value');
		var extra_field = $('#' + current_extra + 'Upload' );
		var text_field = $('#wall-post-status');

		if ( current_extra != "none" && extra_field.attr('value') == "" )
		{
			alert("Please enter a value to submit your extra, otherwise select the cancel link near the input field.");
			return false;
		}
		if ( ( current_extra == "link" || current_extra == "video" ) && !isURL( extra_field.attr('value') ) )
		{
			alert("Please enter a fully qualified URL. e.g. http://www.google.com");
			return false;
		}
		if ( text_field.attr('value') == "" )
		{
			alert("Please enter something into your status box.");
			return false;
		} 
		$('#form-status').submit();
	});
	
	resizeVideoThumbs();
	addDesignerInfoToggle();
	clearEmailMessages();
	hideSuccessMsg();

}); // end $(document).ready(function(){...})

	function stripslashes (str) {
	    return (str+'').replace(/\\(.?)/g, function (s, n1) {
		switch (n1) {
		    case '\\':
			return '\\';
		    case '0':
			return '\u0000';
		    case '':
			return '';
		    default:
			return n1;
		}
	    });
	}


	function isURL(s)
	{
		var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
		return regexp.test(s);
	}

	function callStatusPost( statustext )
	{
		$.ajax({
		      url: "/status/post",
		      type: 'POST',
		      data: ({'text' : statustext, 'return': 'ajax' }),
		      dataType: 'json',
		      success: function( data ){
 			if( data.response == "ok" )
			{
			    $('#current-status').html( statustext );
			}
		      }
		 });
	}

/*
==========================================================================================
*/

	function resizeVideoThumbs(){
		// Rewriting HTML to make IE work
		/*
		newHTML = jQuery(this).html().replace(/width="[0-9]*"/ig, 'width="'+w+'px"');
		newHTML = newHTML.replace(/height="[0-9]*"/ig, 'height="'+h+'px"');
		*/
		jQuery('.news-box-vid').each(function(){
			//w = jQuery(this).innerWidth();
			//h = jQuery(this).innerHeight();
			w = 173;
			h = 113;
			newHTML = jQuery(this).html().replace(/width=("*)[0-9]*("*)/ig, 'width="'+w+'px"');
			newHTML = newHTML.replace(/height=("*)[0-9]*("*)/ig, 'height="'+h+'px"');
			jQuery(this).html(newHTML);
			//alert(newHTML);
		})
	}

/*
==========================================================================================
*/

	function addDesignerInfoToggle(){
	
		$('#profileInfoBox .link_more:eq(0)').click(
			function(){
				$('#profileInfoBox .moreInfo:eq(0)').toggle('fast',
					function() {
						$('#profileInfoBox .link_more:eq(0)').html($('#profileInfoBox .link_more:eq(0)').html().toLowerCase() == "more" ? "Less" : "More");
					}
				);
				return false;
			}
		);
	
	}

/*
==========================================================================================
*/

  function browserCheck(){
		if(isIE() > 0){ // IE not evaluating this correctly. No idea why. It works on other sites.
			jQuery('body').addClass('isIE');
			jQuery('body').addClass('isIE'+isIE());
		}
		else{
			jQuery('body').addClass('notIE');
		}
	}

/*
==========================================================================================
*/

  function isIE(){
    if (jQuery.browser.msie) {
      return parseInt(jQuery.browser.version, 10);
    }
    else{
      return false;
    }
  }


/*
==========================================================================================
*/

	function clearEmailMessages(){
		jQuery('#mailAddresses').focus(function(){
			if(jQuery(this).html() == jQuery(this).attr('defaultMsg')){
				jQuery(this).html('');
			}
		});
		jQuery('#mailAddresses').blur(function(){
			if(jQuery(this).html() == ''){
				jQuery(this).html(jQuery(this).attr('defaultMsg'));
			}
		});
	}

/*
==========================================================================================
*/

	function tweakPager(){
		/* Unset background image if there's no pagination to avoid double horizontal line. Keep block for spacing. */
		if(jQuery('.pagination-block div:visible').length==0){
			jQuery('.pagination-block').css({'background-image':'none'});
		}
		/* Following section added for CSS in IE not possible due to lack of HTML markup */
		else{
			if(jQuery('.browse_options_bar').length > 0){
				jQuery('.pagination-block').addClass('paginationHasFriends');
			}
			else{
				if(jQuery('#topSpace').length == 0){
					jQuery('.pagination-block').addClass('paginationNeedsSpace');
				}
			}
		}
	}

/*
==========================================================================================
*/

	function hideSuccessMsg(){
		jQuery('#editMyAccount .message')
		  .animate({opacity: 1.0}, 3000) /* Essentially pause for 3 seconds as opacity is already 1.0 */
	    .fadeOut('slow');
	}

/*
==========================================================================================
*/

  // Params: None
  // Return vals: current 4-digit year
  // Notes: Typically used for copyright year

  function displayCurrentYear(){
    var currentDate = new Date();
    var currentYear = currentDate.getYear();
    currentYear = (currentYear < 1000) ? currentYear += 1900 : currentYear;
    document.write(currentYear);
  }

/*
==========================================================================================
*/

	function cufonify(){
		// Only runs if Cufon has been loaded
		if(typeof Cufon === 'function'){
			Cufon.replace('#joinApplication .cufonify', { fontFamily: 'TradeGothic' });
			removeEmptyCufons();
		}
	}

/*
=============================================================================================
*/

	function removeEmptyCufons(){

		jQuery('cufontext').each(
			function(){
				if(jQuery(this).html().replace(/\s*/g, '').length == 0 ){
					jQuery(this).parent().remove();
				}
			});
	
	}

/*
=============================================================================================
*/

  var tmoContainer =       'mainNav_topLevel';
  var tmoPrefix =         'tmo_';
  var dropPrefix =         'dropMenu_';

  var baseClass =         'base';
  var overClass =         'over';
  var activeClass =       'active';
  var overActiveClass =   'overActive';
  var hasDropClass =       'hasDrop';
  var dropClass =         'dropMenu';

  var dropWidth =         175; // CSS overrides this if at least one drop exists
  var timerID =           null;
  var timeOut =           200;
  
  var adjust = 0;

  jQuery(document).ready(function () {
    setupDrops();
  });


////////////////////////////////////////////////////////////////////////////////////////////   

  function setupDrops(){
    initializeDrops({dropTriggers:'#mainNav_topLevel a', dropMenus:'#mainNav .dropMenu'});
  }

////////////////////////////////////////////////////////////////////////////////////////////

    function initializeDrops(parameters){

      var dropTriggers = (typeof(parameters['dropTriggers']) == 'undefined') ? '#mainNav_topLevel a' : parameters['dropTriggers'];
      var dropMenus = (typeof(parameters['dropMenus']) == 'undefined') ? '#mainNav .dropMenu' : parameters['dropMenus'];

      jQuery(dropTriggers).hover(
        function(){
          showDrop(getObjInt(jQuery(this).attr("id")));
        },
        function(){
          releaseDrop(getObjInt(jQuery(this).attr("id")));
        }
      );
      jQuery(dropMenus).hover(
        function(){
          lockDrop();
        },
        function(){
          releaseDrop(getObjInt(jQuery(this).attr("id")));
        }
      );

      if(jQuery('.'+dropClass).length > 0){ // If there's at least one drop
        dropWidth = jQuery('.'+dropClass+':first').width(); // Get width of drop and override dropWidth cal set in dropMenuConfig2.js
      }

    }


////////////////////////////////////////////////////////////////////////////////////////////


    function showDrop(objInt){

        resetDrops();
        resetTimer();

        menuObj = jQuery("#"+tmoPrefix+objInt);
        dropObj = jQuery('#'+dropPrefix+objInt);

        if(jQuery(menuObj).hasClass(baseClass)){
            jQuery(menuObj).removeClass(baseClass).addClass(overClass); // Replace class of base with class of over
        }
        if(jQuery(menuObj).hasClass(activeClass)){
            jQuery(menuObj).removeClass(activeClass).addClass(overActiveClass); // Replace class of active with class of overActive
        }

        if(jQuery(dropObj).length > 0){
            jQuery(menuObj).addClass(hasDropClass);
            leftPad = getLeftPad(jQuery(menuObj).attr("id"));
            jQuery(dropObj).show(); // Show drop
            jQuery(dropObj).css({"left" : leftPad});
        }

    }

////////////////////////////////////////////////////////////////////////////////////////////

    function releaseDrop(objInt){
        if(jQuery('#'+dropPrefix+objInt).length > 0){  // If menu item has drop associated with it
            timerID = setTimeout('resetDrops()', timeOut);  // Reset hover status after timeout
        }
        else{
            resetDrops(); // Reset hover status immediately
        }
    }

////////////////////////////////////////////////////////////////////////////////////////////

    function resetDrops(){
        jQuery("."+hasDropClass).removeClass(hasDropClass);
        jQuery("."+overClass).removeClass(overClass).addClass(baseClass); // Replace any class of over with base
        jQuery("."+overActiveClass).removeClass(overActiveClass).addClass(activeClass); // Replace any class of overActive with active
        // jQuery("."+dropClass+":block").hide();  // Hide all drops currently set to display:block
        jQuery("."+dropClass).hide();  // Hide all drops
    }

////////////////////////////////////////////////////////////////////////////////////////////

  function lockDrop(){
        resetTimer();
    }


// [ Helper functions ] ////////////////////////////////////////////////////////////////////////////////////////////

    function getObjInt(objID){
        return objID.split("_")[1];
    }

    ////////////////////////////////////////////////////////////////////////////////////////////

    function resetTimer(){
    clearTimeout(timerID); // Stop timer
  }

    ////////////////////////////////////////////////////////////////////////////////////////////

  function getLeftPad(objID){
        thisButton = document.getElementById(objID);
        button_x = thisButton.offsetLeft; // Can only get this relative to window (not parent) using jQuery
        var leftPad = eval(button_x);
        //calcPos = (jQuery(thisButton).parent().width() - leftPad > dropWidth) ? leftPad : jQuery(thisButton).parent().width() - dropWidth;
        calcPos = (jQuery(thisButton).parents('div').width() + adjust - leftPad > dropWidth) ? leftPad : jQuery(thisButton).parents('div').width() + adjust - dropWidth;
        //alert('if '+jQuery(thisButton).parents('div').width() +' + '+ adjust +' - '+ leftPad +' <= '+ dropWidth +' then '+ calcPos);
        return(calcPos + "px");
    }

//////////////////////////////////////////////////////////////////////////////////////////////

