// extend math function to array prototype
Array.max = function( array ){
    return Math.max.apply( Math, array );
};

Array.min = function( array ){
    return Math.min.apply( Math, array );
};


jQuery.fn.resetSelection = function() {
  return this.each(function(){
    jQuery(this)[0].selectedIndex = 0;
  });
};

function bgwrap(){
    if(($('#wrap').height()/$('#wrap').width()) > ($('#wrap img').height()/$('#wrap img').width())){
        $('#wrap img').height('100%').width('auto');
    } else {
        if ($.browser.msie && ($.browser.version == 6)) {
            $('#wrap img').height($('#wrap').height()).width($('#wrap').width());
        }
        else {
            $('#wrap img').height('auto').width('100%');
        }
    }
}

var pageurl = (location.pathname.lastIndexOf('/')===location.pathname.length-1) ? location.pathname.toLowerCase()+'default.aspx' : location.pathname.toLowerCase();
var sectionurl = location.pathname.substring(0,location.pathname.lastIndexOf('/')+1).toLowerCase()+'default.aspx';

function locmatch(c,l){
    $(c).each(function(){
        var nlink = '';
        if($('a:eq(0)', this).attr('href')){
            var nlink = ($('a:eq(0)', this).attr('href').lastIndexOf('/')===$('a:eq(0)', this).attr('href').length-1) ? $('a:eq(0)', this).attr('href').toLowerCase()+'default.aspx' : $('a:eq(0)', this).attr('href').toLowerCase();
            console.log(nlink)
        }
        if(l===nlink){
            $(this).addClass('selected');
        }
    });
    return;
}

function navInit(){
    $('#sidenav > li').addClass('closed');
    locmatch('#sidenav li',pageurl);
    if($('#sidenav .selected').length===0){
        pageurl = location.pathname.replace(location.pathname.slice(location.pathname.lastIndexOf('/')+1,location.pathname.lastIndexOf('.aspx')),'default').toLowerCase();
        locmatch('#sidenav li',pageurl);
    }
    var ro = $('#sidenav li.selected').parent().parent();
    if (ro.hasClass('closed')){
        $(ro).toggleClass('closed');
    }
}

function loadPageAjax(loc){
    document.body.style.cursor = 'progress';
    if(!$('#ajPage')[0]){
        $('body').append('<div id="ajPage"></div>');
    }
    var pg = loc + ' #pageContent';
    $('#ajPage').load(pg, '', function(){
        var ph = $('#ajPage').height() + 50;
        tb_show('', '#TB_inline?height='+ ph +'&width=650&inlineId=pageContent', '');
        document.body.style.cursor = 'default';
    });
}

function initTabs() {
    $('.tab').hide().eq(0).show();
    $('#tabs li a').click(function() {
        $('.tab').hide().eq($('#tabs li a').removeClass('selected').index(this)).show();
        $(this).addClass('selected');
    }).eq(0).addClass('selected');
}

//function fixContentToTop(){
    //$('#content').css('top', 0);
    //$('#content').css('left', 0);
//}

function showFullWindowSimulator() {
    $('#btnFullWindowSimulator').show();
    $('.simulatorDisclaimer').show();
}

function bookmark() {
    var title = 'APN Outdoor';
    var url = 'http://www.apnoutdoor.com.au/';
    
    if (window.sidebar)
        window.sidebar.addPanel(title, url, '');
    else if(window.opera && window.print) {
        var elem = document.createElement('a');
        elem.setAttribute('href',url);
        elem.setAttribute('title',title);
        elem.setAttribute('rel','sidebar');
        elem.click();
    }
    else if (document.all)
        window.external.AddFavorite(url, title);
    else alert('Hit Ctrl+D (Cmd+D on a Mac) to add bookmark!');
}

$(document).ready(function() {
    navInit();
    
    $('#skipPackages').click(function(){
        $('.tab').hide().removeClass('selected').eq(1).show().addClass('selected');
    });
    
    // Load the background images
    $.getJSON('/BackgroundImages.ashx', function(data) {
        var rand = Math.floor(Math.random()*(data.length));
        $('#wrap img').attr('src', data[rand]).load(function(){
            bgwrap();
        });
    });

    $('#sidenav a:has(strong)').click(function(){
        var i = $('#sidenav li').index($(this).parent()[0]);
        $('#sidenav li').not(':eq('+i+')').addClass('closed');
        $(this).parent().toggleClass('closed');
    });
    
//    $('#panels > li > a').click(function(){
//        var i = $('#panels > li').index($(this).parent()[0]);
//        $('#panels li').not(':eq('+i+')').addClass('closed');
//        $(this).parent().toggleClass('closed');
//        return false;
//    });

    $('#listNewsItems li, #listGallery li').clickpanel();
    
    $('#sidebar #mapoverlay a').toggle(function(){
        $(this).text('Close');
        center = map.GetCenter();
        zoom = map.GetZoomLevel();
        $('#sidemap, #page').css('position', 'static');
        $('#mapwrap').removeClass('inline').addClass('fullscreen');
        map.LoadMap(new VELatLong(47.22, -122.44), 12, 'r', false)
        map.SetCenterAndZoom(center, zoom);
    }, function(){
        $(this).text('Zoom');
        center = map.GetCenter();
        zoom = map.GetZoomLevel();
        $('#sidemap, #page').css('position', 'relative');
        $('#mapwrap').removeClass('fullscreen').addClass('inline');
        map.LoadMap(new VELatLong(47.22, -122.44), 12, 'r', false)
        map.SetCenterAndZoom(center, zoom);
    });
    
    $('.slider').each(function(){
        $('.slides li', this).not(':eq(0)').hide();
        var p = $(this);
        $('.btnBack', this).click(function(){
            var i = $('.slides li', p).index($('.slides li:visible', p)[0]);
            var h = (i-1 === -1) ? ($('.slides li', p).length -1) : i -1;
            $('.slides li:eq('+i+')', p).hide();
            $('.slides li:eq('+h+')', p).show();
        });
        $('.btnNext', this).click(function(){
            var i = $('.slides li', p).index($('.slides li:visible', p)[0]);
            var j = (i+1 === $('.slides li', p).length) ? 0 : i +1;
            $('.slides li:eq('+i+')', p).hide();
            $('.slides li:eq('+j+')', p).show();
        });
    });
    
    
    quickfacts_interval = setInterval("rotate('#listFacts li')",9000);
    $('#listFacts li, #navFacts li').hover(function(){
        clearInterval(quickfacts_interval);
    },function(){
        quickfacts_interval = setInterval("rotate('#listFacts li')",9000);
    });
    
    // Our format sub nav
    $('#listFormatDetail > li').each(function(){
        $(this).addClass('closed');
        $('#listFormatDetail > li .detail').hide();
        $('a.title', this).click(function(){
            if($(this).next().is(':visible')){
                $(this).next().hide();
                $('#listFormatDetail > li').addClass('closed');
            } else {
                $('#listFormatDetail > li .detail').hide();
                $('#listFormatDetail > li').addClass('closed');
                $(this).next().show();
                $(this).parent().removeClass('closed');
            }
        });
    });
    $('#listFormatDetail > li:eq(0) .detail').show().parent().removeClass('closed');
    
    $('.detail .navigation').each(function(){
        if($('li', $(this).prev()).length == 1){
            $('.linkFormatPrevious', this).hide();
            $('.linkFormatNext', this).hide();
        }
    });
    
    $('.linkFormatPrevious').click(function(){
        var c = '#' + $(this).parent().prev().attr('id') + ' li';
        var i = $(c).index($(c+":visible")[0]);
        var h = (i-1 === -1) ? ($(c).length -1) : i -1;
        if ($.browser.msie && ($.browser.version == 6)) {
            $(c+":eq("+i+")").hide();$(c+":eq("+h+")").show();
        } else {
            $(c+":eq("+i+")").fadeOut('fast', function(){$(c+":eq("+h+")").fadeIn();});
        }
    });
    $('.linkFormatNext').click(function(){
        var c = '#' + $(this).parent().prev().attr('id') + ' li';
        var i = $(c).index($(c+":visible")[0]);
        var j = (i+1 === $(c).length) ? 0 : i +1;
        if ($.browser.msie && ($.browser.version == 6)) {
            $(c+":eq("+i+")").hide();$(c+":eq("+j+")").show();
        } else {
            $(c+":eq("+i+")").fadeOut('fast', function(){$(c+":eq("+j+")").fadeIn();});
        }
    });
    
    $('.viewstudy').click(function(){
        var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
        var urlType = $(this).attr('href').toLowerCase().match(urlString);
        if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){
            tb_show($(this).attr('href'), $(this).attr('title'));
            return false;
        } else {
            location.href = $(this).attr('href');
        }
    });
    
    $('.navInsights .view a').click(function(){
        document.body.style.cursor = 'progress';
        if(!$('#ssPpt')[0]){
            $('body').append('<div id="ssPpt"></div>');
        }
        var ppt = $(this).attr('href') + ' #slidePpt';
        $('#ssPpt').load(ppt, '', function(){
            tb_show('Powerpoint slides', '#TB_inline?height=580&width=800&inlineId=ssPpt', '');
            $('#slidePpt ul li:eq(0)').show();
            document.body.style.cursor = 'default';
                $('#ssBack').click(function(){
                    var c = '#slidePpt ul li';
                    var i = $(c).index($(c+":visible")[0]);
                    var h = (i-1 === -1) ? ($(c).length -1) : i -1;
                    if ($.browser.msie && ($.browser.version == 6)) {
                        $(c+":eq("+i+")").hide();$(c+":eq("+h+")").show();
                    } else {
                        $(c+":eq("+i+")").fadeOut('fast', function(){$(c+":eq("+h+")").fadeIn();});
                    }
                });
                
                $('#ssNext').click(function(){
                    var c = '#slidePpt ul li'
                    var i = $(c).index($(c+":visible")[0]);
                    var j = (i+1 === $(c).length) ? 0 : i +1;
                    if ($.browser.msie && ($.browser.version == 6)) {
                        $(c+":eq("+i+")").hide();$(c+":eq("+j+")").show();
                    } else {
                        $(c+":eq("+i+")").fadeOut('fast', function(){$(c+":eq("+j+")").fadeIn();});
                    }
                });
        });
        return false;
    });
    
    $('#viewTestimonial').click(function(){
        var p = $('li:visible blockquote', $(this).parent().parent()).attr('cite');
        loadPageAjax(p);
        return false;
    });
    
    $('#panelCampaigns select').change(function(){
        $('.listCampaigns li').removeClass('selected').hide();
        if($('#panelCampaigns select:eq(0) option').index($('#panelCampaigns select:eq(0) option:selected'))===0 && $('#panelCampaigns select:eq(1) option').index($('#panelCampaigns select:eq(1) option:selected'))===0 && $('#panelCampaigns select:eq(2) option').index($('#panelCampaigns select:eq(2) option:selected'))===0){
            $('.listCampaigns li').not(':eq(0)').addClass('selected');
        } else {
            var filter = [];
            $('#panelCampaigns select').each(function(){
                filter.push($('option:selected', this).val());
            });
            $('.listCampaigns li').not(':eq(0)').each(function(){
                var cat = $('span', this).text().split(',');
                var j = 0;
                if((!filter[0]) || cat[0].indexOf(filter[0])>-1){j++}
                if((!filter[1]) || cat[1].indexOf(filter[1])>-1){j++}
                if((!filter[2]) || cat[2].indexOf(filter[2])>-1){j++}
                if(j>2){
                    $(this).addClass('selected');
                }
            });
        }
        
        if ($('.listCampaigns li.selected').length===0){
            $('.listCampaigns li:eq(0)').show().height('80px').css('padding-top','70px');
        }
        
    });
    
    $('.listCampaigns li a img.lightbox').click(function(){
        tb_show($(this).attr('title'),$(this).attr('href'),'');
        return false;
    });
    
    /*$('#listAudienceInsights').each(function(){
        var pheight = []
        $('p', this).each(function(){
            pheight.push($(this).height());
        }).each(function(){
            var ppad = (Math.max.apply(null, pheight)-$(this).height()) + 'px';
            $(this).css('padding-bottom',ppad);
        });
    });*/
    
    $('.videoplayer').each(function(){
        $(this).click(function(){
            var vid = $(this).attr('href');
            var caption = $(this).attr('title');
            var url = '#TB_inline?height=400&width=640&inlineId=videoWindow';
            swfobject.embedSWF('/Common/Flash/APNOutdoor_videoplayer_01f.swf?movie='+vid, "videoHolder", "640", "360", "9");
            tb_show(caption, url);
            return false;
        });
    });
     
    $('.magnify', $('#listFormatImages').next()).click(function(){
        $('#listFormatImages li:visible:eq(0) a').click();
        return false;
    });
    
    $('#btnFullWindowSimulator').click(function(){
        document.getElementById('apnSimulator').style.top = 0;
        document.getElementById('apnSimulator').style.left = 0;
        document.getElementById('apnSimulator').style.width = '100%';
        document.getElementById('apnSimulator').style.height = '100%';
        $('#apnSimulator h2, #apnSimulator a').show();
        return false;
    });
    
    $('#btnCloseFullscreen').click(function(){
        $('#apnSimulator h2, #apnSimulator a').hide();
        $('#apnSimulator').width(728).height(442);
        $('#apnSimulator').css('left', ($('#videowrap').offset().left+1)+'px').css('top', $('#videowrap').offset().top+'px');
    });
    
    initTabs();
    
    $('#registerBack').click(function(){history.go(-2);return false;});
    
	
	/* news ticker */
	function mycarousel_initCallback(carousel){
		$('<a class="jcarousel-more jcarousel-more-vertical" href="/news/">more news</a>').insertAfter(carousel.buttonPrev);
		// Pause autoscrolling if the user moves with the cursor over the clip.
		carousel.clip.hover(function() {
			carousel.stopAuto();
		}, function() {
			carousel.startAuto();
		});
	};
	
	jQuery('#mycarousel').jcarousel({
        vertical: true,
        scroll: 1,
		auto: 6,
		wrap: 'last',
		animation: 600, 
		initCallback: mycarousel_initCallback,
		buttonNextHTML: '<div class="jcarousel-next jcarousel-next-vertical">next</div>',
		buttonPrevHTML: '<div class="jcarousel-prev jcarousel-prev-vertical">prev</div>'
    });


	

	
    //fixContentToTop();
    
    //$('#bookmark').click(function () { bookmark(); });
});

$(window).resize(function(){
    bgwrap();
});

