/*
	Script: Main
	Project: Toilet Seats Plus
	Author: Primal Consultancy
	Last Update: March 2011
	
	Table of Contents:
						Plugins
						Font Replacement
						Toggle Inputs
						Hover Intents
						Accordion
						Product Colors
						Shopping Cart
						Toggle PC Logo
*/


/* PLUGINS */


/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
/*
 * imgPreview jQuery plugin
 * Copyright (c) 2009 James Padolsey
 * j@qd9.co.uk | http://james.padolsey.com
 * Dual licensed under MIT and GPL.
 * Updated: 09/02/09
 * @author James Padolsey
 * @version 0.22
 */
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);


/*
 * imgPreview jQuery plugin
 * Copyright (c) 2009 James Padolsey
 * j@qd9.co.uk | http://james.padolsey.com
 * Dual licensed under MIT and GPL.
 * Updated: 09/02/09
 * @author James Padolsey
 * @version 0.22
 */
 (function($){
    
    $.expr[':'].linkingToImage = function(elem, index, match){
        // This will return true if the specified attribute contains a valid link to an image:
        return !! ($(elem).attr(match[3]) && $(elem).attr(match[3]).match(/\.(gif|jpe?g|png|bmp)$/i));
    };
    
    $.fn.imgPreview = function(userDefinedSettings){
        
        var s = $.extend({
            
            /* DEFAULTS */
            
            // CSS to be applied to image:
            imgCSS: {},
            // Distance between cursor and preview:
            distanceFromCursor: {top:10, left:10},
            // Boolean, whether or not to preload images:
            preloadImages: true,
            // Callback: run when link is hovered: container is shown:
            onShow: function(){},
            // Callback: container is hidden:
            onHide: function(){},
            // Callback: Run when image within container has loaded:
            onLoad: function(){},
            // ID to give to container (for CSS styling):
            containerID: 'imgPreviewContainer',
            // Class to be given to container while image is loading:
            containerLoadingClass: 'loading',
            // Prefix (if using thumbnails), e.g. 'thumb_'
            thumbPrefix: '',
            // Where to retrieve the image from:
            srcAttr: 'href'
            
        }, userDefinedSettings),
        
        $container = $('<div/>').attr('id', s.containerID)
                        .append('<img/>').hide()
                        .css('position','absolute')
                        .appendTo('body'),
            
        $img = $('img', $container).css(s.imgCSS),
        
        // Get all valid elements (linking to images / ATTR with image link):
        $collection = this.filter(':linkingToImage(' + s.srcAttr + ')');
        
        // Re-usable means to add prefix (from setting):
        function addPrefix(src) {
        	if (src)
            	return src.replace(/(\/?)([^\/]+)$/,'$1' + s.thumbPrefix + '$2');
        }
        
        if (s.preloadImages) {
            (function(i){
                var tempIMG = new Image(),
                    callee = arguments.callee;
                if (typeof s.scrAttr !== 'undefined')
                	tempIMG.src = addPrefix($($collection[i]).attr(s.srcAttr));
                tempIMG.onload = function(){
                    $collection[i + 1] && callee(i + 1);
                };
            })(0);
        }
        
        $collection
            .mousemove(function(e){
                
                $container.css({
                    top: e.pageY + s.distanceFromCursor.top + 'px',
                    left: e.pageX + s.distanceFromCursor.left + 'px'
                });
                
            })
            .hover(function(){
                
                var link = this;
                $container
                    .addClass(s.containerLoadingClass)
                    .show();
                $img
                    .load(function(){
                        $container.removeClass(s.containerLoadingClass);
                        $img.show();
                        s.onLoad.call($img[0], link);
                    })
                    .attr( 'src' , addPrefix($(link).attr(s.srcAttr)) );
                s.onShow.call($container[0], link);
                
            }, function(){
                
                $container.hide();
                $img.unbind('load').attr('src','').hide();
                s.onHide.call($container[0], this);
                
            });
        
        // Return full selection, not $collection!
        return this;
        
    };
    
})(jQuery);
 /*
(function(c){c.expr[':'].linkingToImage=function(a,g,e){return!!(c(a).attr(e[3])&&c(a).attr(e[3]).match(/\.(gif|jpe?g|png|bmp)$/i))};c.fn.imgPreview=function(j){var b=c.extend({imgCSS:{},distanceFromCursor:{top:10,left:10},preloadImages:true,onShow:function(){},onHide:function(){},onLoad:function(){},containerID:'imgPreviewContainer',containerLoadingClass:'loading',thumbPrefix:'',srcAttr:'href'},j),d=c('<div/>').attr('id',b.containerID).append('<img/>').hide().css('position','absolute').appendTo('body'),f=c('img',d).css(b.imgCSS),h=this.filter(':linkingToImage('+b.srcAttr+')');function i(a){return a.replace(/(\/?)([^\/]+)$/,'$1'+b.thumbPrefix+'$2')}if(b.preloadImages){(function(a){var g=new Image(),e=arguments.callee;g.src=i(c(h[a]).attr(b.srcAttr));g.onload=function(){h[a+1]&&e(a+1)}})(0)}h.mousemove(function(a){d.css({top:a.pageY+b.distanceFromCursor.top+'px',left:a.pageX+b.distanceFromCursor.left+'px'})}).hover(function(){var a=this;d.addClass(b.containerLoadingClass).show();f.load(function(){d.removeClass(b.containerLoadingClass);f.show();b.onLoad.call(f[0],a)}).attr('src',i(c(a).attr(b.srcAttr)));b.onShow.call(d[0],a)},function(){d.hide();f.unbind('load').attr('src','').hide();b.onHide.call(d[0],this)});return this}})(jQuery);*/



$(document).ready(function() {

    /* FONT REPLACEMENT */

    // Normal
    Cufon.replace("#logo span, #utils .shipping, .prod-list h2 a, .prod-main h1", { fontFamily: "Colaborate-Regular", hover: true });
    // Bold
    Cufon.replace(".prod-tabs h4, #accord h5, .banner h6, .recent h4, #breadcrumb, table.cart th", { hover: true });



    /* TOGGLE INPUTS */

    function toggle_input(selector) {
        var value = selector.val();
        selector.focus(function() {
            if ($(this).val() == value)
                $(this).val("");
        }).blur(function() {
            if ($(this).val() == "")
                $(this).val(value)
        });
    }

    var logUser = $(".login .user");
    var logPass = $(".login .pass");
    var searchKeys = $("#nav-bar .keywords");
    var returnUser = $(".return input[type=text]");
    var returnPass = $(".return input[type=password]");
    var firstUser = $(".first input[type=text]");
    var firstPass = $(".first input[type=password]");
    var prodQty = $("form.prod-order input");
    var discount = $(".discount input");
    var qty = $(".prod-img input.qty");
    toggle_input(logUser);
    toggle_input(logPass);
    toggle_input(searchKeys);
    toggle_input(returnUser);
    toggle_input(returnPass);
    toggle_input(firstUser);
    toggle_input(firstPass);
    toggle_input(prodQty);
    toggle_input(discount);
    toggle_input(qty);



    /* HOVER INTENTS */

    // Login hover
    var logForm = $(".login form");
    function log_show() { logForm.show(); }
    function log_hide() { logForm.hide(); }
    log_hide();
    $("li.login").hoverIntent({
        over: log_show,
        time: 200,
        out: log_hide
    });

    // Products megamenu hover
    var prodMenu = $("ul#prod-types");
    function prod_show() { prodMenu.show(); }
    function prod_hide() { prodMenu.hide(); }
    prod_hide();
    $("#global-nav .products").hoverIntent({
        over: prod_show,
        time: 200,
        out: prod_hide
    });

    // Select color hover
    var selCol = $("#sel-color ul");
    function col_show() { selCol.show(); }
    function col_hide() { selCol.hide(); }
    col_hide();
    $("#sel-color").hoverIntent({
        over: col_show,
        time: 200,
        out: col_hide
    });

    // OrderBy hover
    var orderBy = $("li.orderby ul");
    function order_show() { orderBy.show(); }
    function order_hide() { orderBy.hide(); }
    order_hide();
    $("li.orderby").hoverIntent({
        over: order_show,
        time: 200,
        out: order_hide
    });


    /* ACCORDION */

    var accordion = $("#accord ul");
    var speed = "fast";
    accordion.hide();
    $("#accord h5")
		.css({ 'cursor': 'pointer' })
		.click(function() {
		    accordion.slideUp(speed).parents("li").removeClass("active");
		    $(this).siblings("ul").slideDown(speed);
		    $(this).parents("li").addClass("active");
		});

    // Accordion imgPreview
    var accordLink = $("#accord ul a");
    accordLink.imgPreview({
        containerID: 'imgPreview',
        imgCSS: { width: 100 },
        srcAttr: 'rel'
    });



	/* PRODUCT COLORS */
	var previewImg = $(".prod-img>img");
	var originalImg = previewImg.attr("src");
	var thereIsSelected = 0; // Boolean
	var currentlySelected; // Stores the selected image source link
    $(".prod-img li a")
		.hover(
			function() {
				previewImg.attr("src", $(this).attr("href")); // Change preview picture
			},
			function() {
				if (thereIsSelected)
					previewImg.attr("src", currentlySelected);
				else
					previewImg.attr("src", originalImg)
			}
		)
		.click(function(e) {
			e.preventDefault();
			thereIsSelected = 1;
			currentlySelected = previewImg.attr("src"); // Needed to change the preview if nothing is re-selected
			
			$("#selected_color").val($(this).attr("rel")); // Update the hidden input
			
			var qty = $(".prod-list input[type=text]"); // The QTY input object
			qty.effect("highlight", {}, 1000);
			if (isNaN(qty.val()) || parseInt(qty.val()) !== parseFloat(qty.val())) { // On first click or invalid input
				qty.val("1");
			}
			
			$(".prod-img li a").removeClass("color-active");
			$(this).addClass("color-active");
		});
	$(".prod-img>img").hover(
		function() {
			$(this).next().hide();
		},
		function() {
			$(this).next().show();
		}
	);
	
	// Validate if a color has been selected on "Add to Cart" action
	$(".prod-img input[type=submit]").click(function(){
		if (!thereIsSelected) {
			alert("Please select a color!");
			return false;
		}
	});



    /* SHOPPING CART */

    $(".cart .total a").click(function() {
        var yes = confirm("Are you sure you want to delete?");
        return (yes) ? true : false;
    });

    // Toggle different shipping address
    var shipping = $("#dif-address");
    shipping.hide();

    $('label.shipping input').bind('click', function() {
        if ($(this).is(':checked')) {
            shipping.show();
        }
        else {
            shipping.hide();
        }
    });


    // Calculations	
    function change_rows() { // Change rows
        $(".cart tbody tr").each(function() {
            var price = $(this).children(".price").text(); // single price
            price = price.substr(3, price.length); // remove $
            price = parseFloat(price);

            var qty = $(this).find(".qty input").val(); // quantity

            if (isNaN(qty) || parseInt(qty) !== parseFloat(qty)) { // on wrong input
                alert("Please enter only valid numbers!");
                return;
            }

            var total = price * qty; // calculate
            $(this).children(".total").html('<a href="#" class="sprite" title="Delete product from shopping cart">&nbsp;</a> $' + total.toFixed(2)); // replace
        });

        // Sum rows
        var data = new Array();
        $(".cart td.total").each(function() {
            row = $(this).text(); // the cell's data
            len = row.length; // the cell's length
            row = row.substr(3, len); // without the $

            data.push(parseFloat(row));
        });

        // Change footer
        var sum = 0;
        for (var i = 0; i < data.length; i++) {
            sum += data[i];
        }
        $(".calc .sub span").text("$" + sum.toFixed(2));
        var shipping = $(".calc .ship span").text();
        shipping = shipping.substr(1, shipping.length);
        sum += parseFloat(shipping);

        var discount = $(".calc .discount span").text();
        discount = discount.substr(3, discount.length);
        sum -= parseFloat(discount);

        $(".calc .total span").text("$" + sum.toFixed(2));
        // alert(data);

        // Unset values

        sum = 0;
        total = 0;
    }

    $("button.update").click(function(e) {
        e.preventDefault();
        change_rows();
    });



    /* TOGGLE PC LOGO */

    var hoverCont = '<span class="black">Primal</span> <span class="blue">Consultancy</span>';
    var isIE7 = navigator.userAgent.toLowerCase().match("msie 7");
    var isWebkit = navigator.userAgent.toLowerCase().match("webkit");
    var topIndent = (isWebkit) ? "-4px" : "0";

    $("a.pclogo").text("").hover(
		function() {
		    if (!isIE7) {
		        $(this)
					.css({
					    'background-position': '9999px',
					    'top': topIndent
					})
					.html(hoverCont);
		    }
		},
		function() {
		    if (!isIE7) {
		        $(this)
					.css({
					    'background-position': '-480px -550px',
					    'top': '10px'
					})
					.html("");
		    }
		}
	);
});
