/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


/* vim: set expandtab tabstop=4 shiftwidth=4: */

var Kosmodisk = (function(){
	
	/**
     * Init common and misc parts of the website
     * 
     * @return void
     */
    var initWebsite = function ()
    {
        // Init TypeKit
        try{Typekit.load();}catch(e){}

        // Init Fancybox
        $('.fancybox').fancybox();

        // Init Forms
        $('input,textarea').each(function() {
            $(this).addClass($(this).attr('type'));

            $(this).focus(function() {
                $(this).addClass('focused');
                $('#' + $(this).attr('id') + '-label').addClass('focused');
            });

            $(this).blur(function() {
                $(this).removeClass('focused');
                $('#' + $(this).attr('id') + '-label').removeClass('focused');
            });
        });

        $('input.submit').wrap(
            '<div class="submit-button" />'
        ).before(
            '<div class="submit-left" />'
        ).after(
            '<div class="submit-right" />'
        ).wrap(
            '<div class="submit-middle" />'
        ).attr(
            'value', 'SUBMIT'
        );

        $('.middle a').click(function(e){
            var msg = "";
            if ($(this).parents('.purchase').find('select[name=Size]')) {
                var selVal = $(this).parents('.purchase').find('select[name=Size]').val();
                if ('' == selVal) {
                    msg += "Please select a size. ";
                }
            }
            if ($(this).parents('.purchase').find('select[name=Colour]')) {
                var selCol = $(this).parents('.purchase').find('select[name=Colour]').val();
                if (0 == selCol) {
                    msg += "Please select a colour. ";
                }
            }
            if ($(this).parents('.purchase').find('select[name=quantityDropdown]')) {
                var selQua = $(this).parents('.purchase').find('select[name=quantityDropdown]').val();
                if (0 == selQua) {
                    msg += "Please select a quantity. ";
                }
            }
            
            if (msg != '') {
                alert(msg);
                return false;
            }
        });
          
        // Style Side Navigation
        if ($('#side-navigation').children().length) {
            $('#side-navigation').show();
            $('#side-navigation').prepend(
                '<img src="/images/layout/sidebar/subnav-top.png" class="top" />'
            ).append(
                '<img src="/images/layout/sidebar/subnav-bottom.png" class="bottom" />'
            );
        }

        // Style Side News Month Navigation
        $('div#custom-doc.news #side-navigation div.cmsWidgetMonths ul').prepend(
            '<li class="static-item">NEWS ARCHIVE</li>'
        ).prepend(
            '<li id="latest-news"><a href="/news/" title="Latest News">Latest News</a></li>'
        );

        if (location.pathname == '/news/') {
            $('div#custom-doc.news #side-navigation div.cmsWidgetMonths ul li#latest-news').addClass('selected');
        }

        // Style Side Products
        $('#side-products').prepend(
            '<img src="/images/layout/sidebar/box-top.png" class="top" />'
        ).append(
            '<img src="/images/layout/sidebar/box-bottom.png" class="bottom" />'
        );

        // Pagination
        $('.cmsListings .pagination:first').insertAfter(
            '.cmsListings h1'
        );

        // Listings Page
        $('.news .cmsListings .listingItem').each(function() {
            var href  = $(this).find('h2 a').attr('href');
            var title = $(this).find('h2 a').text();
            $(this).find('.title').after(
                '<div class="read-more"><a href="' + href + '" title="' + title + '">Full story</a></div>'
            );
        });
        
        $('.searchResults .result').each(function() {
        	var readMore = $(this).find('a.read-more');
        	
        	var href = readMore.attr('href');
        	var title = $(this).find('.title');
        	
        	readMore.wrap('<div class="read-more" />').removeClass('read-more').attr('title', title.text());
        	
        	title.after(
        		$(this).find('.read-more')      	
        	).wrapInner(
        		'<a href="' + href + '" title="' + title.text() + '" />'
        	);
        });

        // FAQ's
        $('.faqs .content-item h2').click(function() {
            $(this).siblings('div.answer').toggle();
        }); 

        // Style Footer Menu
        $('#footer-menu ul li:first').css('border', 'none').css('padding', '0');

        // Testimonial title
        $('#body div.testimonials div.quote').before(
        	'<div class="title"> User Reviews </div>'
        );        	
    };

    var initHeader = function ()
    {
        // Top Bar Text
        if ($('.top-bar-container ul').length) {
            $('.top-bar-container ul').cycle({
                fx:     'fade',
                speed:  1000,
                timeout: 6000,
                height: 'auto',
                width: 'auto',
                fit: 0
                });
        }

        // Shopping Cart
        $('#top-bar .shopping-cart').wrapInner(
            '<div class="middle"></div>'
        ).prepend(
            '<div class="left"></div>'
        ).append(
            '<div class="right"></div>'
        );

        // Header Video Button
        $('.header-video').wrapInner(
            '<div class="middle"></div>'
        ).prepend(
            '<div class="left"><img src="/images/buttons/blue-silver/left.png" /></div>'
        ).append(
            '<div class="right"><img src="/images/buttons/blue-silver/right.png" /></div>'
        );

        // Add arrow to video buttons
        $('.header-video a').after(
            '<img src="/images/buttons/blue-silver/arrow.png" class="arrow" />'
        );

        // Newsletter Sign Up Form
        $('.sign-up-form-container dl dd').each(function() {
            var dtId = '#' + $(this).attr('id').replace('element', 'label');
            var defaultText = $(this).siblings(dtId).text().replace('*', '');
        
            $(this).find('input.text').val(
                defaultText
            ).focus(function() {
                if ($(this).val() == defaultText) {
                    $(this).val('');
                }            
            }).blur(function() {
                if ($(this).val() == '') {
                    $(this).val(defaultText);
                }
            });

        });

        var submitButtonContainer = $('.sign-up-form-container dl .submit-button');
        submitButtonContainer.addClass('long-blue-white-button');
        submitButtonContainer.children('.submit-left').addClass('button-left');
        submitButtonContainer.children('.submit-middle').addClass('button-middle');
        submitButtonContainer.children('.submit-right').addClass('button-right');
        submitButtonContainer.find('input.submit').val('SIGN UP');
        submitButtonContainer.after('<div class="submit-loader"><img src="/images/icons/ajax-loader.gif" /></div>');

        // Create Blank Div For Overlay
        $('#hd').append('<div id="newsletter-overlay" class="simple-overlay"><div class="message" /></div>');
        $('#newsletter-overlay').overlay();
        var overlay = $("#newsletter-overlay").data("overlay");

        $('.sign-up-form-container form').submit(function() {
            var form = $(this);
            var formValues = form.serialize();

            var submitButton = form.find('.submit-button');
            var submitLoader = form.find('.submit-loader');

            // Hide Signup Button
            submitButton.hide();
            submitLoader.show();
            form.find('input').attr('disabled', 'disabled').addClass('disabled');

            // Perfom AJAX Call To Server
            $.ajax({
                type: "POST",
                url: "/ajax/xhr-newsletter-signup/",
                data: formValues,
                success: function(data) {
                    if (data.success == false) {
                        submitButton.show();
                        form.find('input').removeAttr('disabled').removeClass('disabled');
                    }

                    $('#newsletter-overlay .message').html(data.message);
                    overlay.load();
                    submitLoader.hide();
                }
            });

            return false;

        });

        // Style Main Menu
        $('#main-menu ul li').prepend(
            '<span class="left"></span>'
        ).append(
            '<span class="right"></span>'
        );

        $('#main-menu ul li').hover(
            function() {
                $(this).addClass('hovered');
            }, function() {
                $(this).removeClass('hovered');
            }
        );

        $('#main-menu ul.level2').wrap(
            '<div class="menu-level2"></div>'
        );

        $('#main-menu .menu-level2').prepend(
            '<div class="top"></div>'
        ).append(
            '<div class="bottom"></div>'
        );

        $('.menu-level2 li ul.level3').prepend(
            '<div class="top"></div>'
        ).append(
            '<div class="bottom"></div>'
        );
    };
    
    var initHomepage = function ()
    {
    	var maxHeight;
    	
        // Homepage - Products
    	maxHeight = $('.homepage-products .content-item:first').height();
    	$('.homepage-products .content-item').each(function() {
    		if ($(this).height() > maxHeight) {
    			maxHeight = $(this).height();
    		}
    		
   		
    	});
    	
    	$('.homepage-products .content-item').height(maxHeight);    	
    	
        $('#swoosh ul li').click(function() {
            $('#swoosh ul li').removeClass('selected');
            $('#body .content-item').removeClass('selected');

            $(this).addClass('selected');
            $('#body .content-item#' + $(this).attr('id').replace('product-thumbnail', 'product')).addClass('selected');
        });
        
        // Homepage - Product Boxes
        maxHeight = $('#product-boxes .content-item:first').height();
        $('#product-boxes .content-item').each(function() {
            var productType = $(this).children('.snippet-product-type');
            productType.hide();

            $(this).addClass(productType.children('.type').text().toLowerCase());
            $(this).find('.subtitle').after($(this).children('.snippet-image'));

            $(this).find('.price').prepend('Your price:<br />');
            $(this).find('.snippet-more-info').wrap('<div class="container-bottom"></div>')
                                              .after($(this).find('.price'))
                                              .after($(this).find('.snippet-buy-now-link'));

            if ($(this).height() > maxHeight) {
                maxHeight = $(this).height();
            }
        });
        
        $('#product-boxes .content-item').height(maxHeight - 60);

        // Homepage - About Us Bar
        var aboutBar = $('#homepage-about-bar');
        var testimonials = aboutBar.find('.partial-testimonials');
        var feature = aboutBar.find('.basic-feature');
        var maxHeight = (testimonials.height() > feature.height()) ? testimonials.height() : feature.height();

        testimonials.height(maxHeight);
        feature.height(maxHeight);
        aboutBar.height(maxHeight);
        aboutBar.find('.left .middle, .right .middle').height(maxHeight);

        // Homepage - News Bar
        $('#news-bar').prepend(
            '<div class="left">NEWS</div>'
        ).append(
            '<div class="right"><a href="/news/" title="View All News">VIEW ALL NEWS</a></div>' +
            '<div class="arrow"></div>'
        );
    };

    var initDefaultPage = function ()
    {

    };
    
    var initHeaderVideo = function (addLightbox)
    {
    	if (addLightbox) {
	    	var carouselLink = $('.header-video .video-link');
	        var videoSrc = carouselLink.attr('href');
	        
	        videoSrc = videoSrc.replace(
	            new RegExp("watch\\?v=", "i"), 'v/'
	        );
	        
	        videoSrc = videoSrc.replace(
	            new RegExp("\/embed\/", "i"), '/v/'
	        );
	        
	        var fancyboxOptions = {
	            'padding'       : 0,
	            'autoScale'     : false,
	            'transitionIn'  : 'none',
	            'transitionOut' : 'none',
	            'title'         : this.title,
	            'width'         : 750,
	            'height'        : 495,
	            'href'          : videoSrc,
	            'type'          : 'swf',
	            'swf'           : {
	            	'wmode'        		: 'transparent',
	            	'allowfullscreen'   : 'true'
	            }
	        };
	        
	        carouselLink.fancybox(fancyboxOptions);
    	}
        
    	var regEx = new RegExp('showHeaderVideo=true');
    	if (regEx.test(document.location.href)) {
    		$('.header-video .video-link').click();
    	}
    };
    
    var initIframe = function ()
    {
    	var header = $('#hd');
    	
    	// Remove Unnecessary Items
    	$('#bd, #ft').remove();
    	
    	// Remove Badge
    	header.find('.certificate-badge').remove();
    	
    	// Hide Lower Level Navigation
    	header.find('#main-menu .menu ul li .menu-level2').remove();
    	
    	// Convert Each Link To Work Outside iFrame
    	$('a').each(function() {
    		var target = $(this).attr('target');
    		if (!target) {
    			$(this).attr('target', '_top');
    		}
    	});
    	
    	header.find('.header-video a').attr('href', '/products/?showHeaderVideo=true');
    };
    
    return {
        
    	/**
         * Init method
         * 
         * @return  void
         */
        init: function () 
        {
	        var videoLightbox = true;
    	
    		initWebsite();
            initHeader();
            
            if ($('#custom-doc').hasClass('homepage')) {
                initHomepage();
            }

            if ($('#custom-doc').hasClass('default')) {
                initDefaultPage();
            }
            
	        // Only Load iFrame Method
            if (document.location.pathname == '/ajax/iframe-header/'){
	        	initIframe();
	        	videoLightbox = false;
	        }
            
            initHeaderVideo(videoLightbox);
         }        
    };

}());

$(function(){
    setTimeout("Kosmodisk.init()", 500);
});


