$(document).ready(function() {
    $('a').each(function() {
        var a = new RegExp('/' + window.location.host + '/');
        if (!a.test(this.href)) {
            $(this).click(function(event) {
                event.preventDefault();
                event.stopPropagation();
                window.open(this.href, '_blank');
            });
        }
    });

    drawerState = "closed";
    hash = window.location.hash.replace(/^.*#/, '');
    var origContent = "";
    $.history.init(loadContent);
    $(window).bind('resize',
    function() {
        $('#logo').center({
            transition: 300
        });
    });
    $("#formsubmit").live('click',
    function(e) {
        e.preventDefault();
        $('#message').hide();
        var name = $("input#name").val();
        if (name === "") {
            $("label#name_error").show();
            $("input#name").focus();
            return false;
        }
        var email = $("input#email").val();
        if (email === "") {
            $("label#email_error").show();
            $("input#email").focus();
            return false;
        }
        var dataString = 'name=' + name + '&email=' + email;
        $.ajax({
            type: "POST",
            url: "inc/process.php",
            data: dataString,
            success: function(data) {
                $('#formsubmit').fadeOut('fast');
                $('#feedback').fadeIn('slow');
                $('input').val('');
            }
        });
        return false;
    });
    function checkKey(e) {
        if (e.keyCode == 37) {
            if ($('#slides').is(':visible')) {
                $('#slides').cycle('prev');
            } else if ($('#pressers').is(':visible')) {
                $('#pressers').cycle('prev');
            }
        } else if (e.keyCode == 39) {
            if ($('#slides').is(':visible')) {
                $('#slides').cycle('next');
            } else if ($('#pressers').is(':visible')) {
                $('#pressers').cycle('next');
            }
        }
    }
    if ($.browser.mozilla) {
        $(document).keypress(checkKey);
    } else {
        $(document).keydown(checkKey);
    }
    function updateNav($active, justRemove) {
        $active.parents('ul:first').find('.current').removeClass('current');
        if (!justRemove) {
            $active.addClass('current');
        }
    }
    function toggleLoader() {
        var $loader = $('#ajax-loader');
        if ($loader.is(':visible')) {
            $loader.stop().animate({
                'opacity': 0
            },
            'fast', 'linear',
            function() {
                $loader.hide();
            });
        } else {
            $loader.show().stop().animate({
                'opacity': 0.5
            },
            'fast');
        }
    }
    function onAfter(curr, next, opts) {
        var idx = opts.currSlide + 1;
				if($('#subnav').css('height') == '40px'){
					// Don't scroll, mobile device
				} else {
        $(window).scrollTo("#item-" + idx, 500, {
            easing: 'swing',
            offset: -515
        });
				}
        $('.selectedInfo h2').text(shoes[idx]["title"]);
        $('.selectedInfo p').text(shoes[idx]["desc"]);
        $('#product-code').text(shoes[idx]["prodid"]);
        var coll = hash.split('/');
        $('#shareFacebook').attr('href', 'http://www.facebook.com/sharer.php?u=http://biondacastana.com/%23/collection/' + coll[2] + '/' + shoes[idx]["title"] + '/' + opts.currSlide);
        $('#shareTwitter').attr('href', 'http://twitter.com/home?status=' + shoes[idx]["title"] + ' From Bionda Castana: http://biondacastana.com/%23/collection/' + coll[2] + '/' + shoes[idx]["title"] + '/' + opts.currSlide);
        $('.item').removeClass("current");
        $('#item-' + idx).addClass("current");
        $('.selectedInfo').fadeIn();
        $('#slides').fadeIn('slow');
        $('.prev')[idx - 1 === 0 ? 'fadeOut': 'fadeIn']();
        $('.next')[idx - 1 == opts.slideCount - 1 ? 'fadeOut': 'fadeIn']();
        
    }
    function onPressAfter(curr, next, opts) {
        var idx = opts.currSlide + 1;
        $('.selectedInfo h2').text(presspack[idx]["title"]);
        $('.selectedInfo p').text(presspack[idx]["desc"]);
        $('.cutting').removeClass("current");
        $('#press-' + idx).addClass("current");
        $('.selectedInfo').fadeIn();
        if($('#subnav').css('height') == '40px'){
					// Don't scroll, mobile device
				} else {
        $(window).scrollTo("#press-" + idx, 500, {
            easing: 'swing',
            offset: -530
        });
				}
        $('#pressers').fadeIn('slow');
        $('.pressprev')[idx - 1 === 0 ? 'fadeOut': 'fadeIn']();
        $('.pressnext')[idx - 1 == opts.slideCount - 1 ? 'fadeOut': 'fadeIn']();
    }
    function closeHome() {
        $('.content').fadeOut('fast');
        $('.temp').remove();
        $('#logo').hide();
        $('#drawer').slideUp('fast');
        $('#backstretch').remove();
        $('#collection').animate({
            'margin-top': '0'
        },
        "slow");
        $('.item').removeClass("current");
        $(window).scrollTo(0, 500, {
            easing: 'swing',
            offset: -515
        });
        drawerState = "closed";
    }
		function showRandomImage(){
			$.getJSON('inc/images.php', function(data) {
				
				randomise = Math.floor(Math.random() * data.length);

				image = data[randomise].image_url;
				
				 $.backstretch('img/' + image, {
              speed: 500,
              centeredX: false,
              centeredY: true,
							hang: 0
          });

			});
			
		}
    function loadShoe(shoe) {
        $('#pressers').hide();
        $('#slides').show();
        if (drawerState == "closed") {
            $('#collection').animate({
                'margin-top': '480px'
            },
            "slow");
            $('#drawer').slideDown('slow',
            function() {
                drawerState = "open";
                $('#slides').cycle({
                    fx: 'fade',
                    timeout: 0,
                    speed: 500,
                    startingSlide: shoe,
                    prev: '.prev',
                    next: '.next',
                    after: onAfter
                });
            });
        } else {
            $('#slides').cycle(shoe);
            return false;
        }
    }
    function loadStockists() {
        closeHome();
        toggleLoader();
        $('#ajax-target').load('inc/stockists.php',
        function() {
            toggleLoader();
            updateNav($('#linkto-stockists'));
			_gaq.push(['_trackEvent', 'Pageviews', 'View', 'Stockists']);
            $('#subnav').slideUp('fast');
            $('#stockists').fadeIn('slow');
        });
    }
    function loadBlog(post) {
        closeHome();
        toggleLoader();
		
		if(typeof post == "undefined"){
			
			$('#ajax-target').load('inc/blog.php',
	        function() {
	            toggleLoader();
	            updateNav($('#linkto-blog'));
				_gaq.push(['_trackEvent', 'Pageviews', 'View', 'Blog']);
	            $('#subnav').slideUp('fast');
	            $('#blog').fadeIn('slow');
	        });
			
		} else {
			
			$('#ajax-target').load('inc/blog.php?post=' + post + '&time=' + new Date().getTime(),
	        function() {
	            toggleLoader();
	            updateNav($('#linkto-blog'));
				_gaq.push(['_trackEvent', 'Pageviews', 'View', 'Blog']);
	            $('#subnav').slideUp('fast');
	            $('#blog').fadeIn('slow');
	        });
			
		}

        
    }
    function loadContact() {
        toggleLoader();
        closeHome();
        $('#ajax-target').load('inc/contact.php',
        function() {
            toggleLoader();
            updateNav($('#linkto-contact'));
			_gaq.push(['_trackEvent', 'Pageviews', 'View', 'Contact']);
            $('#backstretch, .content, #gallery-page').fadeOut('fast');
            $('#pressers img').fadeOut();
            $('#drawer').slideUp('slow');
            $('#press').animate({
                'margin-top': '0'
            },
            "slow");
            $('.cutting').removeClass("current");
            $(window).scrollTo(0, 500, {
                easing: 'swing',
                offset: -515
            });
            drawerState = "closed";
            $('#sub-profile').show();
            $('#subnav').slideDown('slow');
            $('#contact').fadeIn('slow');
        });
    }
    function loadProfile() {
        closeHome();
        toggleLoader();
        $('#ajax-target').load('inc/profile.php',
        function() {
            toggleLoader();
            updateNav($('#linkto-profile'));
            updateNav($('#linkto-bio'));
			_gaq.push(['_trackEvent', 'Pageviews', 'View', 'Profile']);
            $('#subnav ul').hide();
            $('#sub-profile').show();
            $('#subnav').slideDown('slow');
            $('#profile').fadeIn('slow');
            $.backstretch('img/bc-profile.jpg', {
                speed: 500,
                centeredX: false,
                centeredY: false,
								hang: 0
            });
        });
    }
    function loadCollection(collection, shoe) {
	
				if(typeof collection == "undefined"){
				
					var defaultCollection = $.ajax({
							type:"POST",
							url: 'inc/getDefaultCollection.php',
							dataType: 'json',
							async: false,
							success: function(result) {
								$('#sub-collection a:first').addClass('current');
								collection = result;
							}
						});
				
				}
				
        closeHome();
        toggleLoader();
        $('#ajax-target').load('inc/collection.php?collection=' + collection + '&time=' + new Date().getTime(),
        function() {
            toggleLoader();
            $('#collection').css({
                'opacity': 0,
                'display': 'block'
            }).show();
            shoes = [];
            var a = 1;
            $(".item").each(function(i) {
                shoes[a] = [];
                shoes[a]["title"] = $('.info h2', this).text();
                shoes[a]["desc"] = $('.info p', this).text();
                shoes[a]["prodid"] = $(this).attr('data-code');
                a++;
            });
            updateNav($('#linkto-collection'));
			_gaq.push(['_trackEvent', 'Pageviews', 'View', 'Collection']);
            $('#subnav ul').hide();
            $('#sub-collection').show();
            $('#subnav').slideDown('fast');
            $(".item img").fadeTo(0, 0.1);
            $(".item img").bind("load",
            function() {
                $(this).fadeTo(800, 1);
            });
            $('#collection').masonry({
                itemSelector: '.item',
                isAnimated: false,
                easing: 'swing',
                isFitWidth: true
            }).animate({
                'opacity': 1
            },
            'fast');
            if (typeof shoe != 'undefined') {
                loadShoe(shoe);
            }
            $('.item').click(function(e) {
                e.preventDefault();
                var url = '/collection/shoe';
                var target = $(this).attr("id").replace("item-", "") - 1;
				_gaq.push(['_trackEvent', 'Collection', 'View', $('.info h2', this).text()]);
                loadShoe(target);
            });
            $('.item').hover(function() {
                $('.show', this).fadeIn();
            },
            function() {
                $('.show', this).fadeOut();
            });
        });
    }
    function loadPress() {
        closeHome();
        toggleLoader();
        $('#ajax-target').load('inc/press.php?time=' + new Date().getTime(),
        function() {
            toggleLoader();
            updateNav($('#linkto-press'));
			_gaq.push(['_trackEvent', 'Pageviews', 'View', 'Press']);
            $('#backstretch, .content, #gallery-page').fadeOut('fast');
            $('#sub-profile').show();
            $('#subnav').slideDown('slow');
            $(".cutting img").fadeTo(0, 0.1);
            $(".cutting img").bind("load",
            function() {
                $(this).fadeTo(800, 1);
            });
            $('#press').imagesLoaded(function() {
                $('#press').masonry({
                    itemSelector: '.cutting',
                    isAnimated: false,
                    easing: 'swing',
                    isFitWidth: true
                });
            });
            $('#press').fadeIn('slow');
            presspack = [];
            var b = 1;
            $(".cutting").each(function(i) {
                presspack[b] = [];
                presspack[b]["title"] = $('.info h2', this).text();
                presspack[b]["desc"] = $('.info p', this).text();
                b++;
            });
            $('.cutting').hover(function() {
                $('.show', this).fadeIn();
            },
            function() {
                $('.show', this).fadeOut();
            });
            $('.cutting').click(function() {
                targetClip = $(this).attr("id").replace("press-", "") - 1;
				_gaq.push(['_trackEvent', 'Press', 'View', $('.info h2', this).text()]);
                $('#slides').hide();
                $('#pressers').show();
                if (drawerState == "closed") {
                    $('#press').animate({
                        'margin-top': '480px'
                    },
                    "slow");
                    $('#drawer').slideDown('slow',
                    function() {
                        drawerState = "open";
                        $('#pressers').cycle({
                            fx: 'fade',
                            timeout: 0,
                            speed: 500,
                            startingSlide: targetClip,
                            prev: '.pressprev',
                            next: '.pressnext',
                            after: onPressAfter
                        });
                    });
                } else {
                    $('#pressers').cycle(targetClip);
                    return false;
                }
            });
        });
    }
    function loadCampaigns() {
        toggleLoader();
        $('#ajax-target').load('inc/campaigns.php',
        function() {
            toggleLoader();
            updateNav($('#linkto-campaigns'));
			_gaq.push(['_trackEvent', 'Pageviews', 'View', 'Campaigns']);
            $('.content').fadeOut('fast');
            $('#pressers img').fadeOut();
            $('#drawer').slideUp('slow');
            drawerState = "closed";
            $('#gallery-page').show();
            $('#press').animate({
                'margin-top': '0'
            },
            "slow");
            $('.cutting').removeClass("current");
            $(window).scrollTo(0, 500, {
                easing: 'swing',
                offset: -515
            });
            $('#campaigns').fadeIn('slow');
            $('#sub-profile').show();
            $('#linkto-profile, #linkto-campaigns').addClass('current');
            $('#subnav').slideDown('slow');
            var $campaigns = $('#campaigns'),
            $images = $campaigns.find('.campaignshot'),
            $nav = $('#gallery-page'),
            showing = 1,
						h = $(window).height()-180;
						$(window).resize(function(){
							var h = $(window).height()-180;
							$('#slide').height(h);
							$images.scaleImage({scale: "fit"});
						});
            $images.hide();
						$('#slide').height(h);
						$('#campaign-1').show().scaleImage({scale: "fit"}).appendTo($('#slide'));
            var navString = '',
            i = 1;
            $images.each(function() {
                var current = (i === 1) ? ' current': '';
                navString = navString + '<li class="temp"><a href="#" class="campaignlinks' + current + ' campaign-' + i + '">' + i + '</a></li>';
								
								$(this).click(function() {
		                var next = showing + 1;
		                $images.hide();
		                $('#campaign-' + next).show().appendTo($('#slide')).scaleImage({scale: "fit"});
		                $nav.find('.current').removeClass('current');
		                $('.campaign-' + next).addClass('current');
		                showing = next;
		                if (showing == $images.size()) {
		                    showing = 0;
		                }
		                if (showing == 1) {
		                    $('.caption').fadeIn();
		                } else {
		                    $('.caption').fadeOut('slow');
		                }
		
									});
								
                i++;
            });
            $nav.append(navString);
            $nav.find('a').click(function(e) {
                e.preventDefault();
                var index = parseInt($(this).text(), 10);
                $images.hide();
                $('#campaign-' + index).show().appendTo($('#slide')).scaleImage({scale: "fit"});
                $nav.find('.current').removeClass('current');
                $(this).addClass('current');
                showing = index;
                if (index == 1) {
                    $('.caption').fadeIn();
                } else {
                    $('.caption').fadeOut('slow');
                }
            });
        });
    }
    function loadTerms() {
        toggleLoader();
        closeHome();
        $('#ajax-target').load('inc/terms.php',
        function() {
            toggleLoader();
			_gaq.push(['_trackEvent', 'Pageviews', 'View', 'Terms']);
            $('#backstretch, .content, #gallery-page').fadeOut('fast');
            $('#pressers img').fadeOut();
            $('#drawer').slideUp('slow');
            $('#press').animate({
                'margin-top': '0'
            },
            "slow");
            $('.cutting').removeClass("current");
            $(window).scrollTo(0, 500, {
                easing: 'swing',
                offset: -515
            });
            drawerState = "closed";
            $('#sub-terms').show();
            $('#subnav').slideDown('slow');
            $('#terms').fadeIn('slow');
        });
    }
    function loadContent(hash) {
        switch (hash) {
        case '/collection':
            loadCollection();
            break;
        case '/stockists':
            loadStockists();
            break;
        case '/blog':
            loadBlog();
            break;
        case '/profile':
            loadProfile();
            break;
        case '/biography':
            loadProfile();
            break;
        case '/press':
            loadPress();
            break;
        case '/contact':
            loadContact();
            break;
        case '/campaigns':
            loadCampaigns();
            break;
        case '/terms':
            loadTerms();
            break;
				case '/':

				showRandomImage();

            $('#logo').center(true);
            $('#logo').fadeIn(1200);
            break;
        default:
            if (hash !== '') {
                var data = [];
                data = hash.split('/');
                if (data[1] == 'collection') {
                    loadCollection(data[2]);
                }
				if (data[1] == 'blog') {
                    loadBlog(data[2]);
                }
            } else {
	
				showRandomImage();
                $('#logo').center(true);
                $('#logo').fadeIn(1200);
            }
            break;
        }
    }
		$('.collection-link').live('click',
		function(e){
			e.preventDefault();
			var coll = $(this).attr('data-collection');
			//toggleLoader();
			loadCollection(coll);
			$('.collection-link').removeClass('current');
			$(this).addClass('current');
			var url = '/collection/' + coll;
			window.location.hash = url.replace(/^.*#/, '');
		});
    $('#toplogo').click(function(e) {
        e.preventDefault();
        closeHome();
        var url = '/';
        window.location.hash = url.replace(/^.*#/, '');
        closeHome();
        $('#subnav').slideUp('fast');
        showRandomImage();
        $('#logo').center(true);
        $('#logo').fadeIn(1200);
        $('.current').removeClass('current');
    });
    $('#nav-main a, #sub-profile a').click(function(e) {
        e.preventDefault();
        var url = '/' + $(this).attr('id').split('-')[1];
        if (url === '/bio') {
            url = '/' + $('#linkto-profile').attr('id').split('-')[1];
        }
        window.location.hash = url.replace(/^.*#/, '');
        if (url === '/campaigns') {
            window.location.reload(true);
        }
        $('#linkto-terms').live('click',
        function(e) {
            e.preventDefault();
            var url = '/terms';
            window.location.hash = url.replace(/^.*#/, '');
        });
    });
    $('#drawer .footer, #sub-collection a').live('click',
    function(e) {
        e.preventDefault();
        $('#slides img').fadeOut();
        $('#pressers img').fadeOut();
        $('#drawer').slideUp('slow');
        $('#collection').animate({
            'margin-top': '0'
        },
        "slow");
        $('#press').animate({
            'margin-top': '0'
        },
        "slow");
        $('.item').removeClass("current");
        $('.cutting').removeClass("current");
        $(window).scrollTo(0, 500, {
            easing: 'swing',
            offset: -515
        });
        drawerState = "closed";
    });
});
