// GoogleMaps Loader

function GoogleMapsLoader(lat, lon, zoom, city, direquest){
    if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map"));
        map.addControl(new GSmallZoomControl());
        map.addControl(new GMapTypeControl());
        
        map.setCenter(new GLatLng(lat, lon), zoom);
        
        var dwicon = new GIcon();
        dwicon.image = "http://www.designworks.co.nz/images/dwweb-core/d-marker.png";
        
        var parkicon = new GIcon();
        parkicon.image = "http://www.designworks.co.nz/images/dwweb-core/parking.png";
        parkicon.iconSize = new GSize(20, 20);
        
        
        if (city == "well") {
            parkicon.iconAnchor = new GPoint(43, -60);
            dwicon.iconAnchor = new GPoint(24, 18);
            myPOV = {
                yaw: 200.64659986187695,
                pitch: -10
            };
            fullcity = "Wellington";
        }
        
        if (city == "auck") {
            parkicon.iconAnchor = new GPoint(90, -10);
            dwicon.iconAnchor = new GPoint(30, 10);
            myPOV = {
                yaw: 210.64659986187695,
                pitch: -15
            };
            fullcity = "Auckland";
        }
        $("#fullcityname").html("I'm in greater " + fullcity + ", driving from:");
        
        var parking = new GLatLng(lat, lon);
        var point = new GLatLng(lat, lon);
        dwparking = new GMarker(parking, parkicon);
        dwmarker = new GMarker(point, dwicon);
        map.addOverlay(dwmarker);
        map.addOverlay(dwparking);
        
        GEvent.addListener(dwmarker, "click", function(){
            document.getElementById('pano').style.display = "block";
            var myPano = new GStreetviewPanorama(document.getElementById("pano"));
            designworks = new GLatLng(lat, lon);
            myPano.setLocationAndPOV(designworks, myPOV);
            GEvent.addListener(myPano, "error", handleNoFlash);
        });
    }
}

function initialsetup(){
    //find the longest pageholder
    $('#navplaceholder').clone().appendTo('#viewtypebox, #footer #pages');
}

function findcurrentpage(hash){
    lastclicked = $(".mousehover[title='" + hash + "']").parent("div").attr("id");
    currentpage = lastclicked.substr(7, 5);
    pageon = ($(".mousehover[title='" + hash + "']").closest(".pageholders").attr("id")).substr(7, 5);
    pageleft = Number("-" + (pageon * 964 - totalpages));
    if (Number(pageleft)) {
        pageleft += "px";
    }
    else {
        pageleft = '0px';
    }
    return false;
}

function showform(office){
    $(".formarea img:eq(0)").attr('src', office);
    $(".formarea, #fillarea").fadeIn(500);
}

function loadDynamicPage(hash){
    if (hash) {
        // restore ajax loaded state
        if ($.browser.msie) {
            // jquery's $.load() function does't work when hash include special characters like aao.
            hash = encodeURIComponent(hash);
        }
        
        findcurrentpage(hash);
        
        pageshowing = 1;
        $("#fillarea").fadeTo(300, .8);
        $('.prevnext a').css({
            'font-weight': 'normal',
            'font-size': '13px',
            'color': '#666'
        });
        $("#pagewrapper").css('padding-bottom', '1000px');
        $("#pagedisplay").html('');
        $("#footer").fadeOut(300);
        $("#pageborder").fadeIn(10, function(){
            $("#pageborder").css({
                'position': 'absolute'
            });
            
            $("#pagedisplay").load(hash + " #standardpage", function(){
                setuplightbox();
                $("#pagedisplay").fadeIn(200, function(){
                    $(".loader").fadeOut(30);
                });
                
                $.scrollTo("#pagewrapper", 40, {
                    easing: 'easeInSine'
                });//specify an easing equation
                
						if (showstate == -1) {
							$("#contenttray").animate({
								left: pageleft
							}, 1000, "easeInOutQuad", function(){
								$(".prevnext span a:eq(" + pageon + "), li .prevnext span a:eq(" + pageon + ")").css({
									'font-weight': 'bold',
									'font-size': '16px',
									'color': '#000000'
								});
							});
						}
                
            });
            
        });
        
        
    }
    else {
        // start page
        $("#pagedisplay").empty();
        $("#pageborder, #fillarea").fadeOut(0);
    }
}

function setuplightbox(){
    $('#imagegallery img').wrap(function(){
        return '<a href="' + $(this).attr('src') + '" />';
    });
    if ($('#imagegallery img').length % 2 != 0) {
        $('#imagegallery img:last').css({
            'width': '420px',
            'height': '315px'
        });
    }
    
    $(function(){
        $('#imagegallery a').lightBox({
            overlayBgColor: '#ffee00',
            overlayOpacity: 0.6,
            imageLoading: 'images/dw2010-core/lightbox-ico-loading.gif',
            imageBtnClose: 'images/dw2010-core/lightbox-btn-close.gif',
            imageBtnPrev: 'images/dw2010-core/lightbox-btn-prev.gif',
            imageBtnNext: 'images/dw2010-core/lightbox-btn-next.gif',
            containerResizeSpeed: 350,
            txtImage: 'Gallery Image ',
            txtOf: 'of'
        });
    });
}

function googleanalytics() {

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-8617240-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

}



//var sets for handlers
var pageshowing = -1;
var lastpos = 0;
var lastclicked = "article0";
var ratio;
var maxjump;
var tposition = 0;
var list;
var listshow;
var loadericon = '<div class="loader" ><p><img src="images/dw2010-core/loader.gif"/> Loading the page. </p></div>';
var currentpage = 0;
var pageleft = 0;
var totalpages = $('.pageholders').length;
var divtouse;
var showstate=-1;

$(document).ready(function(){

    googleanalytics();

    pageloaded = $(window).attr('href');
    
    $.historyInit(loadDynamicPage, pageloaded);
    
    initialsetup();
    
	$(".showall").live('click', function(event){
		event.preventDefault();
		$('.prevnext a').css({
            'font-weight': 'normal',
            'font-size': '13px',
            'color': '#666'
        });
		
		if(showstate == -1) {

			$('.pageholders').css({'clear':'left'});
			$('.pageholders').fadeTo(100, 1);
			$(".showall").html('show pages');
			$(".prevnext span.pagenums, #footer .prevnext span.pagenums").fadeOut(100);
			totalpages = $('.pageholders').length;
            $("#contentholder").css('height', ($("#nextset0").height() * (totalpages)) + "px");
			$("#contenttray").css('left','0px');
            			showstate = 1;
		}
		else {
			$('.pageholders').css('clear','none');
			$(".showall").html('show all');
			$(".prevnext span.pagenums, #footer .prevnext span.pagenums").fadeIn(100);
			$("#contentholder").css('height', ($("#nextset0").height() + 50) + "px");
			$(".prevnext span a:eq(0), li .prevnext a:eq(0)").css({
                'font-weight': 'bold',
                'font-size': '16px',
                'color': '#000000'
            });
		    showstate = -1;
		}
	});
	
	
    $("#contentholder").css('height', ($("#nextset0").height() + 50) + "px");
    
    if ($(".triggered").length > 0 || $(".fb_invalid").length > 0) {
        $(".formarea").fadeIn(200);
    }
    
    if ($("#resulttext").length > 0) {
        $("#navigation .clearfix li a").html($("#resulttext").html());
    }
    
    
    if ($("#largetextonblack").length > 0) {
        $("#contentholder").css('height', ($("#largetextonblack").height() + 50) + "px");
    }
	
    $("#fillarea").css('height', $("#pagewrapper").height() - 20);
    $(".list-normal:first").css('border-top', '4px solid #444');
    $(".about-people #nextset0").css('border-bottom', '6px solid #444');
    
    $(".closer").live('click', function(event){
        $(".formarea, #fillarea").fadeOut(500);
    });
    
    
    $("#topnav li:last").addClass('last');

    $('.prevnext a').live('click', function(event){
        event.preventDefault();
		$('.prevnext a').css({
            'font-weight': 'normal',
            'font-size': '13px',
            'color': '#666'
        });
		$(".pageholders").fadeTo(100, .2);
		if(showstate==1) {
			$(".pageholders").fadeTo(100, 1)
		}
		$("#nextset" + Number($(this).index())).fadeTo(500, 1);
		
        pageleft = Number("-" + ($(this).index()) * 964 - totalpages);
        divtouse = Number($(this).index());
        if (pageshowing == 1) {
            $("#pageborder").fadeOut(400, function(){
                $('#fillarea').fadeOut(500);
                $("#nextstory, #prevstory").show();
                pageshowing = -1;
            });
        }
        if(showstate==-1) {
        $("#contenttray").animate({
            left: pageleft
        }, 1000, "easeInOutSine", function(){
				$(".prevnext span a:eq(" + divtouse + "), li .prevnext span a:eq(" + divtouse + ")").css({
                'font-weight': 'bold',
                'font-size': '16px',
                'color': '#000000'
            });
        });
        }
        
        
        return false;
    });
    
    $(".mousehover, .list-medium .mousehover, .list-normal .mousehover").live('mouseover mouseout', function(event){
        if (event.type == 'mouseover' && pageshowing == -1) {
            $(this).css({
                'opacity': '.4',
                'filter': 'alpha(opacity=40)'
            });
        }
        else {
            $(this).css({
                'opacity': '0',
                'filter': 'alpha(opacity=0)'
            });
        }
    });
    
    
    $("#contentholder h4").live('mouseover mouseout', function(event){
        if (event.type == 'mouseover') {
            $(this).css({
                'background': '#ffee00'
            });
        }
        else {
            $(this).css({
                'background': 'none'
            });
        }
    });
    
    $(".list-medium .mousehover, .list-normal .mousehover").live('click', function(event){
        event.preventDefault();
        $(".expanded").hide(300);
        $("#contentholder").css('height', 'auto');
        pagelink = $(this).attr('title');
        $("div.summary").fadeIn(50);
        $(this).siblings("div.expanded").html(loadericon).load(pagelink + " #standardpage", function(){
            $(this).siblings("div.summary").hide(0);
            $(this).show(400);
        });
    });
    
    
    $(".expanded").live('click', function(event){
        event.preventDefault();
        $(this).hide(150, function(){
            $(this).siblings("div.summary").show(50);
        });
    });
    
    
    $(".boxtype-1up .mousehover, .boxtype-2up .mousehover,.boxtype-6up .mousehover, .boxtype-25up .mousehover").live('click', function(event){
        if (pageshowing == -1) {
            $(".loader").fadeIn(30);
            $("#fillarea").fadeTo(300, .8);
            $("#pagewrapper").css('padding-bottom', '1000px');
            $("#footer").fadeOut(300);
            currentdiv = $(this).parent("div.boxtypeholder").attr('id');
            currentpage = currentdiv.substr(7, 5);
            
            lastclicked = currentdiv;
            pagelink = $(this).attr("title");
			

            pageshowing = 1;
            
            // set the page number
            $("#pageborder").fadeIn(500, function(){
                $("#pageborder").css({
                    'position': 'absolute'
                });
                $.scrollTo("#pagewrapper", 1000, {
                    easing: 'easeInOutSine',
                    onAfter: function(){
                    
                        $("#pagedisplay").load(pagelink + " #standardpage", function(){
                            $('<img class="dimg" src="images/dw2010-core/d-end-article.gif" />').appendTo("#content p:last");
                            setuplightbox();
                            $("#pagedisplay").fadeIn(200, function(){
                                $(".loader").fadeOut(30);
                            });
                        });
                    }
                });
            });
            googleanalytics();
            historylink = pagelink.replace(/^.*#/, '');
            $.historyLoad(historylink);
            return false;
        }
        
    });
    
    
    $(".relateditemsholder a ").live('click', function(event){
        event.preventDefault();
        $("#nextstory, #prevstory").hide();
        thislink = $(this).attr('title');
        $.scrollTo("#pagewrapper", 1000, {
            easing: 'easeInOutSine',
            onAfter: function(){
                $("#pagedisplay").load(thislink + " #standardpage", function(){
                
                    $('<img class="dimg" src="images/dw2010-core/d-end-article.gif" />').appendTo("#content p:last");
                    setuplightbox();
                    $(".loader").fadeOut(30);
                });
            }
        });
        historylink = thislink.replace(/^.*#/, '');
        $.historyLoad(historylink);
        return false;
    });
    
    
    $("#nextstory, #prevstory").live('click', function(event){
        $(".loader").fadeIn(30);
        $('.prevnext a').css({
            'font-weight': 'normal',
            'font-size': '13px',
            'color': '#666'
        });
        
        switch ($(this).attr("id")) {
            case 'prevstory':
                currentpage--;
                if (currentpage < 0) {
                    currentpage = $("div.boxtypeholder").length - 1;
                }
                break;
            case 'nextstory':
                currentpage++;
                if (currentpage > $("div.boxtypeholder").length - 1) {
                    currentpage = 0;
                }
                break;
            default:
        }
        
        pageon = ($("#article" + currentpage).closest(".pageholders").attr("id")).substr(7, 5);
        
        if (pageon < 0 || showstate == 1) {
            pageon = 0;
        }

        pageleft = Number("-" + (pageon * 964) - totalpages);
        
        $(".mousehover").css({
            'opacity': '0',
            'filter': 'alpha(opacity=0)',
            'background': '#ffee00'
        });
        startarea = $("#article" + currentpage).parent("div").children("h4").children("a").html();
        lastclicked = $("#article" + currentpage).attr('id');
        pagelink = $("#article" + currentpage + " .mousehover").attr("title");
  
        
        $("#pagedisplay").load(pagelink + " #standardpage", function(){
            $('<img class="dimg" src="images/dw2010-core/d-end-article.gif" />').appendTo("#content p:last");
            setuplightbox();
            $("#pagedisplay").fadeIn(200, function(){
                $(".loader").fadeOut(30);
            });
        });
		$(".pageholders").fadeTo(100, 1);
		if (showstate == -1) {
			$("#contenttray").animate({
				left: pageleft
			}, 1000, "easeInOutQuad", function(){
				$(".prevnext span a:eq(" + pageon + "), li .prevnext span a:eq(" + pageon + ")").css({
					'font-weight': 'bold',
					'font-size': '16px',
					'color': '#000000'
				});
			});
		}
              historylink = pagelink.replace(/^.*#/, '');
        $.historyLoad(historylink);
        return false;
    });
    
    
    $(".googcloser").click(function(){
        $("#googlemapsinfo").fadeOut(150);
        $("#footer").fadeIn(500);
    });
    
    $("#showakmap").click(function(){
        if ($("#googlemapsinfo").css('display') == 'none') {
            $("#showakmap").html('[ close map ]');
            $("#googlemapsinfo").css('margin-left', '0');
            //$(".citytype").html("I'm in greater Auckland, driving from:");
            //$("#gofind").attr("onclick", "GoogleMapsLoader(-36.844833, 174.767344, 17, 'auck', '"+$('#fromaddress').attr('value')+"')");
            $("#googlemapsinfo").fadeIn(150, function(){
                GoogleMapsLoader(-36.844833, 174.767344, 17, "auck", "enter street or suburb");
            });
        }
        
        else {
            $("#googlemapsinfo").fadeOut(150);
            $("#showakmap").html('[ show map ]');
        }
    });
    
    $("#showwlgmap").click(function(){
        if ($("#googlemapsinfo").css('display') == 'none') {
            $("#showwlgmap").html('[ close map ]');
            $("#googlemapsinfo").css('margin-left', '480px');
            //$(".citytype").html("I'm in greater Wellington, driving from:");
            //$("#gofind").attr("onclick", "GoogleMapsLoader(-41.292447, 174.778372, 17, 'well', '"+$('#fromaddress').attr('value')+"')");
            $("#googlemapsinfo").fadeIn(150, function(){
                GoogleMapsLoader(-41.292447, 174.778372, 17, "well", "enter street or suburb");
            });
        }
        
        else {
            $("#googlemapsinfo").fadeOut(150);
            $("#showwlgmap").html('[ show map ]');
        }
    });
    
    $("#closebox, #fillarea").live('click', function(){
        if (pageshowing == 1) {
            
            $("#footer").fadeIn(50);
            $("#pageborder").fadeOut(500, function(){
                $('#fillarea').fadeOut(300, function(){
                
                    scrolltest = $("#article" + currentpage).position();
                    if (scrolltest.top > 600) {
                        $.scrollTo("#article" + currentpage, 1000, {
                            easing: 'easeInSine'
                        });
                    }
                });
                
            });
            $("#pagedisplay").html('');
            $("#nextstory, #prevstory").show();
            $(".mousehover").css({
                'opacity': '0',
                'filter': 'alpha(opacity=0)',
                'background': '#ffee00'
            });
            $("#" + lastclicked + " div.mousehover").css({
                'opacity': '.2',
                'filter': 'alpha(opacity=20)',
                'background': '#36a7e9'
            });
            lastclicked = '';
            pageshowing = -1;
            $("#pagewrapper").css('padding-bottom', '0px');
            
            var pageon = ($("#article" + currentpage).closest(".pageholders").attr("id")).substr(7, 5);
            if (pageon < 0) {
                pageon = 0;
            }
			if (showstate == 1) {
			pageon=0;
			}
            pageleft = "-" + Number((pageon * 964 - totalpages));
            		if (showstate == -1) {
						$("#contenttray").animate({
							left: pageleft
						}, 1000, "easeInOutQuad", function(){
							$(".prevnext span a:eq(" + pageon + ")").css('font-weight', 'bold');
						});
					}
            historylink = "";
            $.historyLoad(historylink);
            
            return false;
            
        }
    });
    
    $(".work-work ul li a").live('click', function(event){
        event.preventDefault();
        pageshowing = -1;
        $("#pageborder").fadeOut(150, function(){
            $("#fillarea").fadeOut(50);
        });
        $("#menu-subarea").fadeIn(400);
        $("#menu-subarea div ul li a").removeClass('selected');
        $("#navigation ul li a").removeClass('selected');
        $("#navigation ul li a").removeClass('currentpage');
        
        $(this).addClass('selected');
        
        list = 1;
        
        $("#menu-subarea div").fadeOut(0);
        
        switch ($(this).attr('href')) {
            case 'work-by-offering.html':
                $("#list-by-offering").fadeIn(50);
                break;
            case 'work-by-sector.html':
                $("#list-by-sector").fadeIn(50);
                break;
            case 'work-by-brand.html':
                $("#list-by-brand").fadeIn(50);
                break;
            case 'work.html':
                list = -1;
                $('#contentholder').animate({
                    top: 0
                }, {
                    duration: 400,
                    easing: 'easeInOutQuad',
                    queue: false
                });
                
                $('#viewtypebox, .prevnext, #navplaceholder').html('');
                $("#contenttray").html(loadericon).load("filter-script.html", {
                    'currentpage': '185'
                }, function(){
                
                    $('#contenttray').animate({
                        left: 0
                    }, {
                        duration: 200,
                        easing: 'easeInOutQuad',
                        queue: false
                    });
                    $('#navplaceholder').clone().appendTo('#viewtypebox, #footer #pages');
                    $('#pageborder').css('top', '112px');
                });
                break;
            default:
        }
        
        if (list != -1) {
            $('#contentholder').animate({
                top: 125
            }, {
                duration: 200,
                easing: 'easeInOutQuad',
                queue: false
            });
            $('#fillarea').animate({
                top: 125
            }, {
                duration: 400,
                easing: 'easeInOutQuad',
                queue: false
            });
            $('#pageborder').css('top', '237px');
        }
    });
    
    $("#menu-subarea div ul li a").live('click', function(event){
        event.preventDefault();
        $("#menu-subarea div ul li a").removeClass('selected');
        $(this).addClass('selected');
        menufilter = $(this).attr('title');
        //alert(menufilter);
        $('#viewtypebox, .prevnext, #navplaceholder').html('');
        $("#contenttray").html(loadericon).load("filter-script.html", {
            'currentpage': menufilter
        }, function(){
            $('#contenttray').animate({
                left: 0
            }, {
                duration: 200,
                easing: 'easeInOutQuad',
                queue: false
            });
            $('#contentholder #navplaceholder').clone().appendTo('#viewtypebox, #footer #pages');
        });
        
        if (pageshowing == 1) {
            $('#fillarea').fadeOut(50);
            $("#footer").fadeIn(50);
            $("#pageborder").fadeOut(50);
            $("#pagedisplay").html('');
            
            $(".mousehover").css({
                'opacity': '0',
                'filter': 'alpha(opacity=0)',
                'background': '#ffee00'
            });
            $("#" + lastclicked + " div.mousehover").css({
                'opacity': '.2',
                'filter': 'alpha(opacity=20)',
                'background': '#36a7e9'
            });
            lastclicked = '';
            pageshowing = -1;
            $("#pageborder").css({
                'height': 'auto'
            });
            $("#pagewrapper").css('padding-bottom', '0px');
            
            pageon = ($("#article" + currentpage).closest(".pageholders").attr("id")).substr(7, 5);
            pageleft = Number("-" + (pageon * 964 - totalpages));
            if (pageon < 0) {
                pageon = 0;
            }
            $("#contenttray").animate({
                left: pageleft
            }, 1000, "easeInOutQuad", function(){
                $(".prevnext span a:eq(" + pageon + ")").css('font-weight', 'bold');
            });
            
            pageshowing = -1;
            
            historylink = "";
            $.historyLoad(historylink);
            
            return false;
        }
        
    });
    
    
    $(".aboutsection a").live('click', function(event){
        event.preventDefault();
        $(".aboutsection ul li a").removeClass('selected');
        $(this).addClass('selected');
        menubar = "Section";
        menutext = $(this).html();
        $("#contenttray").html(loadericon).css('height', '2000px').load("filter-script.html", {
            'menutype': menubar,
            'filter': menutext
        }, function(){
            initialsetup();
            $("#contentholder").css('height', '')
        });
    });
    
});
