//Dropdown menu
$(function() {
        var $mainNav = $('#main-nav'),
        navWidth = $mainNav.width();
        
        $mainNav.children('#main-nav li').hover(function(ev) {
            var $this = $(this),
            $dd = $this.find('ul');
            
            // get the left position of this tab
            var leftPos = $this.find('a').position().left;
            
            // get the width of the dropdown
            var ddWidth = $dd.width(),
            leftMax = navWidth - ddWidth;
            
            // position the dropdown
            $dd.css('left', Math.min(leftPos, leftMax) );
            
            // show the dropdown
            $this.addClass('main-nav-item-active');
        }, function(ev) {
    
            // hide the dropdown
            $(this).removeClass('main-nav-item-active');
        });
    });

$(document).ready(function(){
						   
	// external links
	$("a[rel='external']").attr('title', function() { return this.title + ' (Opens in New Window)' }).click(function() { window.open(this.href); return false; });
	
	//cycle the images on homepage
	$(".slider").cycle({ 
		fx:    'fade', 
		speed:  5000,
		pager:	'.coin_nav',
		pagerAnchorBuilder: coins,
		cleartype: false //stops IE putting a white background color
	});
	
	function coins(i, el) {
		return '<div class="coin"></div>';
	}
	
	// clear 4th menu block
	$("#main-nav li ul li:nth-child(4n+5)").addClass("clear");
	
	// remove margin on last item
	$("#product_list li:nth-child(4n+4)").addClass("noMargin");
	// clear the row above
	$("#product_list li:nth-child(4n+1)").addClass("clear");
	
	
	//Tabbed content on homepage
	$(".tab_content").hide(); //Hide all content
	$("ul.tabs li:first").addClass("active").show(); //Activate first tab
	$(".tab_content:first").show(); //Show first tab content
	$("ul.tabs li").click(function() {
		$("ul.tabs li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$(".tab_content").hide(); //Hide all tab content
		var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
		$(activeTab).fadeIn(); //Fade in the active ID content
		return false;
	});

	// place labels inside input boxes
	$("input").labelify();
	
	if($("#our_price_display").length > 0) {
	
		$('#buy_block select').change( function() {
			calculate_cc();		
		});
		
		calculate_cc();	
		
	}
	function calculate_cc()
	{
		$cc_initial_string = $('#our_price_display').html();
		$cc_initial_string = $cc_initial_string.replace(',', '');
		
		var cc_num = $cc_initial_string.match(/[\d\.]+/g);
		$cc_cash_price = Number(cc_num[0]);
		
		$cc_deposit_price = $cc_cash_price/10;
		$cc_credit_amount = $cc_cash_price-$cc_deposit_price;
		$cc_monthly_payments = $cc_credit_amount/6;
		
		$cc_pound = '&pound;';
		
		$('.cash_price').html($cc_pound+($cc_cash_price.toFixed(2)));
		$('.deposit').html($cc_pound+($cc_deposit_price.toFixed(2)));
		$('.credit_amount').html($cc_pound+($cc_credit_amount.toFixed(2)));
		$('.repayments').html($cc_pound+($cc_monthly_payments.toFixed(2)));
	}
	

});

/**
 * jQuery.labelify - Display in-textbox hints
**/
jQuery.fn.labelify = function(settings) {
  settings = jQuery.extend({
    text: "title",
    labelledClass: ""
  }, settings);
  var lookups = {
    title: function(input) {
      return $(input).attr("title");
    },
    label: function(input) {
      return $("label[for=" + input.id +"]").text();
    }
  };
  var lookup;
  var jQuery_labellified_elements = $(this);
  return $(this).each(function() {
    if (typeof settings.text === "string") {
      lookup = lookups[settings.text]; // what if not there?
    } else {
      lookup = settings.text; // what if not a fn?
    };
    // bail if lookup isn't a function or if it returns undefined
    if (typeof lookup !== "function") { return; }
    var lookupval = lookup(this);
    if (!lookupval) { return; }

    // need to strip newlines because the browser strips them
    // if you set textbox.value to a string containing them    
    $(this).data("label",lookup(this).replace(/\n/g,''));
    $(this).focus(function() {
      if (this.value === $(this).data("label")) {
        this.value = this.defaultValue;
        $(this).removeClass(settings.labelledClass);
      }
    }).blur(function(){
      if (this.value === this.defaultValue) {
        this.value = $(this).data("label");
        $(this).addClass(settings.labelledClass);
      }
    });
    
    var removeValuesOnExit = function() {
      jQuery_labellified_elements.each(function(){
        if (this.value === $(this).data("label")) {
          this.value = this.defaultValue;
          $(this).removeClass(settings.labelledClass);
        }
      })
    };
    
    $(this).parents("form").submit(removeValuesOnExit);
    $(window).unload(removeValuesOnExit);
    
    if (this.value !== this.defaultValue) {
      // user already started typing; don't overwrite their work!
      return;
    }
    // actually set the value
    this.value = $(this).data("label");
    $(this).addClass(settings.labelledClass);

  });
};
