var nav = 'home';
var subnav = "";
var loaded = false;
var loading = false;
var folio_loaded = false;
var current_id = "";
var sliding = true;
var is_scrolling = false;
var current_height=0;
var menu_hover_colour = "#000000";
var is_animating = false;
var height_tolerance = 15;

function Contact()
{
    $("#load").empty();
    var loadUrl="pages/sendEmail.php";
    $("#load").load(loadUrl,{
	enquiry:$("#enquiry").val(),
	name:$("#name").val(),
	email:$("#em").val(),
	tel:$("#tel").val(),
	company:$("#company").val(),
	hu:''
    },function(responseText){
	$("#load").html(responseText);
    });
}

function InitContact()
{
    $("#send-us-an-email").click(function(){
       Contact(); 
    });
}

function InitMap()
{
    var CassetteStyles = [
    {
      featureType: "all",
      stylers: [
        { hue: "#7f00ff" }, { saturation: 15 }
      ]
    }
  ];

  // Create a map object, and include the MapTypeId to add
  // to the map type control.
  var latlng = new google.maps.LatLng(-37.829274,144.99719);
    var mapOptions = {
      zoom: 16,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

 var marker = new google.maps.Marker({
      position: latlng,
      title:"Cassette"
  });

var map = new google.maps.Map(document.getElementById('map-canvas'),
    mapOptions);
    marker.setMap(map); 
    map.setOptions({styles: CassetteStyles});
}


function InitExpandableCopy()
{
    $(".read-more").click(function(e){
        e.preventDefault();
        if ($(".expanded").length){
                $(".expanded").fadeOut(function(){
                    $(this).removeClass('expanded');
                }); 
            
         }
         $(this).parent().next().fadeIn().addClass('expanded'); 
    });
    
    $(".read-less").click(function(e){
        $(this).parent().fadeOut().removeClass('expanded');
        
    });
}

function SplashPage()
{
          $(document).mousemove(function(event) {
            if (loaded == true){
                $(document).unbind('mousemove', function(){return;});
                $('.splash').delay(5000).fadeOut(600, function(){});
                    $('.splash-in').delay(5650).fadeIn(500, function(){
                        if (folio_loaded == false)
                            InitFolio();
                        return
                        ;});
                    return;
                }
        });
        var top_img = new Image();
        $(top_img).attr({src : site_url + "/images/gui/team.jpg"});
	$(top_img).load(function(){ 
            $(top_img).css({width: top_img.width + 'px', height: top_img.height + 'px',display:'none'});
            $("#intro-pic").removeClass('preload').append(this);
                $("#intro-pic img").fadeIn('slow', function(){loaded = true;});
            });
}

function Wheel(event){
        
       if (is_scrolling == true)
            {
              is_scrolling = false;
              if (!event) /* For IE. */
                event = window.event;
                if (event.preventDefault)
                    event.preventDefault();
                    $("html, body").stop(true, true, function(){
                });
            event.returnValue = false;
         }
}

function BindScroll()
{
    if (window.addEventListener)
        /** DOMMouseScroll is for mozilla. */
        window.addEventListener('DOMMouseScroll', Wheel, false);
        /** IE/Opera. */
        window.onmousewheel = document.onmousewheel = Wheel;
}



function InitFolio()
{
    folio_loaded = true;
    BindScroll();
    $('.nivoSlider').nivoSlider({
        effect: 'fade', // Specify sets like: 'fold,fade,sliceDown'
        startSlide: 0,
        slice:1,        // Set starting Slide (0 index)
        directionNav: false, // Next & Prev navigation
        directionNavHide: false, // Only show on hover
        controlNav: true, // 1,2,3... navigation
        controlNavThumbs: false, // Use thumbnails for Control Nav
        keyboardNav: true, // Use left & right arrows
        pauseOnHover: true, // Stop animation while hovering
        manualAdvance: false, // Force manual transitions
        captionOpacity: 0.8, // Universal caption opacity
        prevText: 'Prev', // Prev directionNav text
        nextText: 'Next', // Next directionNav text
        beforeChange: function(){}, // Triggers before a slide transition
        afterChange: function(){
            if (sliding == false)
                {
                    var slide_id = $(".nivo-imageLink:visible img").attr('id');
                    if ($("#" + slide_id).parent().attr('rel')){
                        ProcessFolioClick(slide_id);
                    }
               }
        }, // Triggers after a slide transition
        slideshowEnd: function(){}, // Triggers after all slides have been shown
        lastSlide: function(){}, // Triggers when last slide is shown
        afterLoad: function(){
            
            
        } // Triggers when slider has loaded
    });
    InitSlidersLinks();

}


function InitSlidersLinks()
{
    InitCloseFolio();
    $(".nivo-imageLink").click(function(e){
        e.preventDefault();
        ProcessFolioClick($(this).children("img").attr('id'));
    });
}

function InitCloseFolio(){
 $("#close-folio").click(function(e){
     e.preventDefault();
      $("#folio-item-" + current_id).fadeOut(function(){
          $("#close-folio").fadeOut(1200);
          $('#folio-items-wrapper').stop().animate({
            height: 16}, 1500,'easeInOutExpo', function(){
            current_id = "";
            current_height= 0;
            sliding = true;
            $('.nivoSlider').data('nivo:vars').stop = false;
        });
         is_scrolling = true;
          $("html,body").stop().animate({
            scrollTop: $("body").offset().top}, 1500,'easeInOutExpo', function(){
            });
        }); 
      });
}


function InitFolioPictures(nb_to_load, current_pic_index)
{ 
    if (!nb_to_load)
    {
        $("#folio-item-" + current_id).addClass('loaded').height(current_height)
        .data("wrapper_height", current_height + 59);
                $('#folio-items-wrapper').removeClass('preload-folio').stop().animate({
            height: current_height + 59}, 1500,'easeInOutExpo', function(){
            is_scrolling = true;
            $("html, body").stop().animate({scrollTop: $("#folio-items-wrapper").offset().top}, 1500,'easeInOutExpo');
                $("#folio-item-" + current_id + ", #folio-item-" + current_id + " img").fadeIn("slow", function(){
                $("#close-folio").fadeIn('slow');
                });
            });
        return;
       
    }
    var folio_img = new Image();
    $(folio_img).attr({src : site_url + "/" 
            + $("#" + current_id)
        .attr("src")
        .split(".jpg")
        .join(current_pic_index + ".jpg")})
    .load(function(){  
        $("#folio-item-"+ current_id).append("<div></div>").append(this);
        $(this).css({width: this.width + 'px', height: this.height + 'px', display:'none'});
        current_height += this.height + 20; // folio item margin-top
        InitFolioPictures((--nb_to_load), ++current_pic_index);
    });
    return;
}

function ProcessFolioClick(id_click){
        if (sliding == true){
                $('.nivoSlider').data('nivo:vars').stop = true;
                sliding = false;
            }
        if (id_click == current_id && current_height > 0){
            is_scrolling = true;
            $("html, body").stop().animate({scrollTop: $("#folio-items-wrapper").offset().top}, 1500,'easeInOutExpo', function(){
                 });
                return;
        }
        if (current_height > 0){
            $("#folio-item-" + current_id).fadeOut("fast", function(){});
        }
        current_id = id_click;
        if ($("#folio-item-" + current_id).hasClass('loaded')){
                    $('#folio-items-wrapper').stop().animate({height: $("#folio-item-" + current_id).data('wrapper_height')}, 1500,'easeInOutExpo', function(){
                        $("#close-folio").fadeIn('slow', function(){});
                        is_scrolling = true;
                        $("#folio-item-" + current_id).fadeIn("slow", function(){
                        $("html, body").stop().animate({scrollTop: $("#folio-items-wrapper").offset().top}, 1500,'easeInOutExpo');
                    });
             });
            return;
        }
        var start_index = 2; // INDEX OF FIRST IMAGE (FILENAME)
        var nb_to_load = $("#" + id_click).parent().attr('rel');
        if (nb_to_load)
            {
                current_height = 0;
                $('#folio-items-wrapper').addClass('preload-folio');
                    //$("html, body").stop().animate({scrollTop: $("#folio-items-wrapper").offset().top}, 1500,'easeInOutExpo');
                     $("#folio-items-wrapper").append("<div id='folio-item-" + current_id + "' class='folio-item'></div>");
                    InitFolioPictures(nb_to_load, start_index);                  
            }

        return;
}

function InitCloseWebSubFolio()
{
   $("#close-folio").click(function(e){ 
       e.preventDefault();
      $("#folio-items-" + current_id).data('nivo:vars').stop = true;
       $("#folio-items-" + current_id).fadeOut(function(){
           $("#close-folio").fadeOut(1000);
           $('#sub-folio-items-wrapper').animate({
            height: 0, "padding-top":0, "margin-top":0}, 1500,'easeInOutExpo', function(){
            current_id = "";
            sliding = true;
            $('.nivoSlider').data('nivo:vars').stop = false;
            });
            is_scrolling = true;
             $("html, body").stop().animate({
            scrollTop: $("body").offset().top}, 1500,'easeInOutExpo', function(){
            });
       });
       
    });
}

function InitWebFolioPictures(nb_to_load, current_pic_index, id_click)
{ 
    if (!nb_to_load)
    {
        $("#folio-items-" + id_click).addClass('loaded');
         if (sliding == false)
                {
                    $("#folio-items-" + current_id).data('nivo:vars').stop = true;
                   $("#folio-items-" + current_id).fadeOut("fast", function(){$("#folio-items-" + id_click).fadeIn()}); 
                }
            else
                $("#folio-items-" + id_click).fadeIn();
            $("#folio-items-" + id_click).nivoSlider({
                effect: 'fade', // Specify sets like: 'fold,fade,sliceDown'
                startSlide: 0,
                slice:1,        // Set starting Slide (0 index)
                directionNav: false, // Next & Prev navigation
                directionNavHide: false, // Only show on hover
                controlNav: true, // 1,2,3... navigation
                controlNavThumbs: false, // Use thumbnails for Control Nav
                keyboardNav: false, // Use left & right arrows
                pauseOnHover: true, // Stop animation while hovering
                manualAdvance: true, // Force manual transitions
                captionOpacity: 0.8, // Universal caption opacity
                prevText: 'Prev', // Prev directionNav text
                nextText: 'Next', // Next directionNav text
                beforeChange: function(){
                }, // Triggers before a slide transition
                afterChange: function(){
                }, // Triggers after a slide transition
                slideshowEnd: function(){}, // Triggers after all slides have been shown
                lastSlide: function(){}, // Triggers when last slide is shown
                afterLoad: function(){} // Triggers when slider has loaded);
            });
            
            current_id = id_click;
            sliding = false;
            return;
       
    }
    var folio_img = new Image();
    var url = site_url + "/images/web/featured/" + id_click + "/" + id_click + ".screen" + current_pic_index + ".jpg";
    $(folio_img).attr({src : url})
      .load(function(){
        $(this).css({width: this.width + 'px', height: this.height + 'px'});
        $("#folio-items-" + id_click).append(this);
        InitWebFolioPictures((--nb_to_load), ++current_pic_index, id_click);
    });
    return;
}


function ProcessWebFolioClick(id_click){
    
    //current_id = id_click;
    var nb_to_load =  $("#folio-items-" + id_click).attr('rel');
    $('#sub-folio-items-wrapper').animate({
            height: 450, 'padding-top':17}, 1500,'easeInOutExpo', function(){
                 
         });
         is_scrolling = true;
         $("html").stop()
                 .animate({scrollTop: $("#sub-folio-items-wrapper")
                     .offset()
                     .top - 10},
                 1500,'easeInOutExpo', function(){
                     if ($("#folio-items-" + id_click).hasClass('loaded')){
                         if (id_click != current_id && current_id)
                             {
                                $("#folio-items-" + current_id).data('nivo:vars').stop = true;
                                $("#folio-items-" + current_id).stop().fadeOut("fast", function(){
                                    $("#folio-items-" + id_click).fadeIn("slow", function(){
                                        $('#folio-items-' + id_click).data('nivo:vars').stop = false;
                                         current_id = id_click;
                                        });
                                    
                                }); 
                                 
                             }
                             else{
                                    $("#folio-items-" + id_click).fadeIn(function(){
                                        $('#folio-items-' + id_click).data('nivo:vars').stop = false;
                                        current_id = id_click;
                          });
                         }
                            
                    }
                    else
                        {
                            InitWebFolioPictures(nb_to_load, 1, id_click);
                     }
                     $("#close-folio").fadeIn('slow', function(){});
                 });   
}


function InitSubSlidersLinks()
{
    InitCloseWebSubFolio()
    $(".nivo-imageLink").click(function(e){
        e.preventDefault();
        
        $('.nivoSlider').data('nivo:vars').stop = true;
        id_click = $(this).children("img").attr('id');
        if (!($("#folio-items-" + id_click)).size())
            {
                window.location = $(this).attr('href');
                return;
            }
        $('#web-slider').data('nivo:vars').stop = true;
        ProcessWebFolioClick(id_click);
        
    });
}



function InitWebFolio()
{
    folio_loaded = true;
    BindScroll();
    $("#web-slider").nivoSlider({
        effect: 'fade', // Specify sets like: 'fold,fade,sliceDown'
        startSlide: 0,
        slice:1,        // Set starting Slide (0 index)
        directionNav: false, // Next & Prev navigation
        directionNavHide: false, // Only show on hover
        controlNav: true, // 1,2,3... navigation
        controlNavThumbs: false, // Use thumbnails for Control Nav
        keyboardNav: false, // Use left & right arrows
        pauseOnHover: true, // Stop animation while hovering
        manualAdvance: false, // Force manual transitions
        captionOpacity: 0.8, // Universal caption opacity
        prevText: 'Prev', // Prev directionNav text
        nextText: 'Next', // Next directionNav text
        beforeChange: function(){}, // Triggers before a slide transition
        afterChange: function(){
            if (sliding == false)
                {
                    var slide_id = $(".nivo-imageLink:visible img").attr('id');
                    if (($("#folio-items-" + slide_id)).size())
                        ProcessWebFolioClick(slide_id);
               }
        }, // Triggers after a slide transition
        slideshowEnd: function(){}, // Triggers after all slides have been shown
        lastSlide: function(){}, // Triggers when last slide is shown
        afterLoad: function(){
            
            
        } // Triggers when slider has loaded
    });
    InitSubSlidersLinks()

}

function InitMenus()
{     
     if (nav != "home")
            $("#nav-" + nav).addClass('current-page');
     if (subnav != "")
            $("#" + subnav).addClass('current-copy');
     $("#top-menu a, #copy-menu a, .header-merry-xmas a").hover(function(){
              if ((("nav-" +  nav) && (subnav)) != $(this).attr("id")){
                     $(this).stop().animate({"color": menu_hover_colour}, 350); 
                }},function(){
    if ("nav-" +  nav != $(this).attr("id")){
                $(this) .stop()
                        .animate({"color": "#b0b1b1"}, 250);} 
                });
    $("#copy-menu a").click(function(e){
        e.preventDefault();
        if (!is_animating){
                $("#copy-loading").show();
                var id_clicked = $(this).attr('id');
               is_animating = true;
               $("#" + subnav).animate({"color": "#b0b1b1"}, 250).removeClass("current-copy");
               $("#" + id_clicked).addClass("current-copy");
               $("#" + subnav + "-copy").fadeOut('fast', function(){
                   $("#" + subnav + "-copy").removeClass('default-copy');
                   if (Math.abs($('#main-copy-wrapper').height() - ($("#" + id_clicked + "-copy")
                   .height() + 60)) > height_tolerance){
                   $('#main-copy-wrapper').stop().animate({
                    height: (($("#" + id_clicked + "-copy").height() + 60)+ "px")}, 1500,'easeInOutExpo', function(){
                            $("#copy-loading").fadeOut();
                            $("#" + id_clicked + "-copy").fadeIn('slow', function(){
                               is_animating = false;
                               subnav = id_clicked;
                            });
                        });
                   }else{
                       $("#copy-loading").fadeOut();
                            $("#" + id_clicked + "-copy").fadeIn('slow', function(){
                               is_animating = false;
                               subnav = id_clicked;
                            });
                   }
                  
               });
            }
    });
}


function InitCarousel(item_to_scroll)
{
    $('.carousel').jcarousel({
        easing: "easeInOutExpo",
        scroll:item_to_scroll,
        animation:1100
    }
);
}

function InitZoom()
{
    $('.cloud-zoom').CloudZoom();
    
}

$(document).ready(function(){
    InitMenus();
    switch(nav)
{
    case "home":
      SplashPage();
      break;
    case "design":
      InitFolio();
      break;
       case "about":
      InitZoom();
      break;
      case "print":
      InitFolio();
      InitExpandableCopy();
      break;
      case "web":
      InitCarousel(4);
      InitExpandableCopy();
      InitWebFolio();
      break;
     case "real-estate":
      InitExpandableCopy();
      InitWebFolio();
      break;
     case "contact":
      InitMap();
      InitContact();
      break;
     case "testimonials":
      InitCarousel(1);
      InitExpandableCopy();
      break;
     default:
      break;
}

	setup_social_media_handlers();
	setup_rollovers();

});

function setup_social_media_handlers() {$(".fb-link").click(function(e) { fbs_click(location.href); e.preventDefault(); return false;});$(".twt-link").click(function(e) {twt_click(location.href,"Merry Xmas from Cassette!"); e.preventDefault(); return false;});}
function fbs_click(url) { window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(url),'sharer','toolbar=0,status=0,width=626,height=436'); return false; }
function twt_click(url,title) { window.open('http://www.twitter.com/share?url='+url.replace(" ","+")+'&text='+title.replace(" ","+"),'sharer','toolbar=0,status=0,width=626,height=436');return false; }
function setup_rollovers() {
	$("body").append("<div id='i_preload' />");
	var buttons = ["/images/merry-xmas/facebook_butt_roll.jpg", "/images/merry-xmas/twitter_butt_roll.jpg"];
	for(var i = 0;i<buttons.length;i++) {
		$("#i_preload").append("<div style='background:url(" + site_url + buttons[i] + ");position:absolute;left:-1000px;top:-1000px;height:200px;width:200px;'></div>");
	}
}
