var x;
var y;
var slidepos = new Array();
var pageid;
var slideid = 0;
var tier3id;
var tier3active;
var tier3flag = false;

$(document).ready(function(){
	$('#slideInner').hide();
	$.getImages('#slideInner div','#container',$.init);
	$.linkElement('#logo', 'home.aspx');
});
$.setWinRes = function () {
    $(window).resize(function () {
        $('.tier3page').show();
        $('#navigationSub a').unbind('click');
        $('#controlLeft').unbind('click');
        $('#controlRight').unbind('click');
        $('.callTier3Page').unbind('click');
        $.fitinWindow('#container');
        $.fitinWindow('#slideOuter');

        $.fitinWindow('#slideInner', 'h');
        $.fitinWindow('.page');
        $.fitinWindow('.tier3page');

        slidepos = $.getSlidePositions();

        $.setContentVertical();
        $.setTier3ContentVertical();

        $.imgResize('.pagebg img');
        //$.imgResize('.tier3pagebg img');

        $.setSubNaviPosCalls();

        $.setSlideControlPosCalls();
        $.updateSlidePosition();
        $.checkForTier3Calls();
    });
}
$.init = function () {
    $('.preloadr').fadeOut().remove();

    $('#slideInner').fadeIn();
    $.fitinWindow('#container');
    $.fitinWindow('#slideOuter');

    $.fitinWindow('#slideInner', 'h');
    $.fitinWindow('.page');
    $.fitinWindow('.tier3page');

    if ($('#navigationSub a').length > 1) {
        setTimeout(function () {
            $('#navigationSub').css({ top: '90px', opacity: '0' });
            $('#navigationSub').animate({ top: '115', opacity: '0.8' }, 500, 'swing');
        }, 300);
    } else {
        $('#navigationSubBg').hide();
        $('#navigationSub').hide();
        $('.slideControls').hide();
    }

    if ($.QuirksModeAlert() == 'Quirks') {
        $('.content').width('450');
    }
    slidepos = $.getSlidePositions();

    $.setContentVertical();
    $.setTier3ContentVertical();

    $.imgResize('.pagebg img');

    $.imgResize('.tier3pagebg img');

    $.setSubNaviPosCalls();
    $.getPageId();
    $.checkForTier3Calls();
    $.setSlideControlPosCalls();
    $.setActiveLinkColor();
    if ($('video').length > 0) {
        VideoJS.setupAllWhenReady();
    }
    setTimeout('$.setWinRes()', 1000);
}

/*********************************/
$.linkElement = function(myElement,myLink){ // adds link to selected element currently only the top byapp-logo/index.aspx is set with this 
		$(myElement).bind('click',function(){
			window.location.href = myLink;
		});
	}

$.updateSlidePosition = function(){ // called on win resize due to slide pos changes when resize occurs, without it pages slide out of viewport on resize
	//console.log(slidepos);
	//console.log(slideid);
	//console.log(slidepos[slideid]);
	$('#slideInner').css({
		left: slidepos[slideid]
	});
}

$.pauseMedia = function(pageid,slideid){ // pause occurs when video slided out of viewport, works where with HTML5 supported
	if(Modernizr.video && $('.video-js-box video').hasClass('vjs-playing') == true){
		//console.log('#page'+pageid+'Sub'+slideid+'_video paused');
		$('#page'+pageid+'Sub'+slideid+'_video')[0].player.pause();
	}
}

$.setActiveLinkColor = function(){ // main navi & sub content selector navi link color update + left/right slide arrows are controled here 
    if (slideid > 0) { // left arrow gets hidden on leftmost content box
			$('#controlLeft').fadeIn(500);
		}else{
			$('#controlLeft').fadeOut(500);
		}if (slideid < slidepos.length - 1) { // right arrow gets hidden on rightmost content box 
			$('#controlRight').fadeIn(500);
		}else{
			$('#controlRight').fadeOut(500);
		}
	$('#navigationMain a').removeClass();
	$('#page' + pageid + 'homeNavi').addClass('active');
	$('#navigationSub a').removeClass();
	$('#page' + pageid + 'Sub' + slideid + 'Navi').addClass('active');
}

$.setContentVertical = function () { // calculates & sets content holders to vertical middle pos. which are change on win.resize
    var doubleContentHeights = new Array();
    $('#slideInner').find('.doubleContent').each(function (i) {
        var $temp = $('.doubleContent:eq(' + i + ')');
        doubleContentHeights[i] = $temp.height(); // store different content holder heights
        //console.log(doubleContentHeights[i]);
        $('.doubleContent:eq(' + i + ')').css({
            top: $.setVertical(doubleContentHeights[i])
        });
        $('.pagebg:eq(' + i + ')').css({
            left: -slidepos[i]
        });
        if ($temp.children('div:eq(1)').length > 0) { // if there are two content boxes in the holder their vert.pos set separately, margin is used to position shorter box to middle
            // there are two situations: 'box[0] heigth < box[1] height' this is what is set up below
            // for 'box[0] heigth > box[1] height' is not considered
            var $margintop = ($temp.children('div:eq(1)').height() - $temp.children('div:eq(0)').height()) / 2;
            //console.log($margintop);
            if ($margintop > 0) {
                $temp.children('div:eq(0)').css({
                    margin: $margintop + 'px 20px 0 0'
                });
            } else if ($margintop < 0) {
                $temp.children('div:eq(1)').css({
                    top: -$margintop + 'px'
                });
            }
        }
    });
}
$.setTier3ContentVertical = function(){ // currently the watches page has tier3 content = content boxes that fades in when links clicked
	//console.log(tier3flag);
	var tier3DoubleContentHeights = new Array();
	$('#slideInner').find('.tier3Content').each(function(i){
		var $temp = $('.tier3Content:eq('+i+')');
		tier3DoubleContentHeights[i] = $temp.height(); // store content holder heights & set vertical. middle
		//console.log(tier3DoubleContentHeights[i]);
		$('.tier3Content:eq('+i+')').css({
			top: $.setVertical(tier3DoubleContentHeights[i])
		});
if ($temp.children('div:eq(1)').children().length > 0) { // if there are two content boxes in the holder their vert.pos set separately, margin is used to position shorter box to middle    // there are two situations: 'box[0] heigth < box[1] height' this is what is set up below    // for 'box[0] heigth > box[1] height' is considered here as well
			var $leftBox = $temp.children('div:eq(0)').height();
			var $rightBox = $temp.children('div:eq(1)').height();
			if ($leftBox > $rightBox || $leftBox == $rightBox) {
				var $margintop = ($temp.children('div:eq(0)').height() - $temp.children('div:eq(1)').height())/2;
				$temp.children('div:eq(1)').css({
					margin: $margintop+'px 0 0 0'
				});
                } else if ($leftBox < $rightBox) {
				var $margintop = ($temp.children('div:eq(1)').height() - $temp.children('div:eq(0)').height())/2;
				$temp.children('div:eq(0)').css({
					margin: $margintop+'px 20px 0 0'
				});
			}
			//console.log('Tier3 margintop = '+$margintop);
		}
	});
}

$.getImages = function(imgSource,preloadHolder,callback){ // image preload
	//console.log('images to load = '+$(imgSource).length);
	if ($(imgSource).length > 0) {
		$(preloadHolder).append('<div class=preloadr>0%</div>');
		var szImages = new Array();
		$(imgSource).find('img').each(function () {
		    //alert($(this).attr('src'));
		    szImages.push($(this).attr('src'));
		})

		var oPreload = new ImagePreload(szImages, callback);

	}
}

$.getPageId = function(){ // get page id from tag id
	var temp = $('div.home').attr('id').match(/[\d\.]+/g);
	pageid = temp[0];
	return pageid;
}

$.updatePageId = function(myElement,id){
	var temp = $(myElement).attr('id').match(/[\d\.]+/g);
	pageid = temp[0];
	if(slideid == undefined || slideid == NaN){slideid = temp[1];}
	tier3id = temp[2];
	if(id){
	return temp[id];
	}else{
	//console.log('page '+pageid+' Sub '+slideid+' Sub '+tier3id)
	return [pageid,slideid,tier3id];
	}
}

$.IEalert = function(){ // ie version check
	if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){
		var iever =new Number(RegExp.$1);
		return iever;
	}
}

$.QuirksModeAlert = function(){ // ie mode check
	var mode=document.compatMode;
	if(mode){
		if(mode == 'BackCompat'){
			mode='Quirks';
		}else if(mode == 'CSS1Compat'){
			mode='Standards Compliance';
		}else{
			mode='Almost Standards Compliance';
		}
	}
	return mode;
}

$.fitinWindow = function(myElement,w_h){
	x = $(window).width();
	y = $(window).height();
	switch (w_h){
		case 'h':
			$(myElement).height(y);
			break;
		case 'w':
			$(myElement).width(x);
			break;
		default:
			$(myElement).width(x);
			$(myElement).height(y);
			break;
	}
}

$.setVertical = function(myHeight){
	return (y/2 - myHeight/2);
}

$.imgResize = function(imgArray){
    //resize img one by one
	/*for(var i=0;i<$(imgArray).length;i++){ 

		var img_x = $(imgArray+':eq('+i+')').width();
		var img_y = $(imgArray+':eq('+i+')').height();

		var newimg_x = x;
		var newimg_y = x / img_x * img_y;
		//console.log('original: '+img_x+' x '+img_y);
		//console.log('new: '+newimg_x+' x '+newimg_y);
		if(newimg_y < y){
			var newimg_x = y / img_y * img_x;
			var newimg_y = y;
			//console.log('renew: '+newimg_x+' x '+newimg_y);
		}
		$(imgArray+':eq('+i+')').width(newimg_x);
		$(imgArray+':eq('+i+')').height(newimg_y);
	}*/
    //resize img by taking first img params and resize others according to those params, 
    //means all img has to have the same aspect ratio
	var img_x = $(imgArray+':eq(0)').width(); 
	var img_y = $(imgArray+':eq(0)').height();

	var newimg_x = x;
	var newimg_y = x / img_x * img_y;

	if(newimg_y < y){
		newimg_x = y / img_y * img_x;
		newimg_y = y;
	}
	//console.log('orig: '+img_x+' x '+img_y);
	//console.log('new :'+newimg_x+' x '+newimg_y);

	for(var i=0;i<$(imgArray).length;i++){
		$(imgArray+':eq('+i+')').css('width',newimg_x);
		$(imgArray+':eq('+i+')').css('height',newimg_y);
	}
}

$.getSlidePositions = function(){ // calculate & store left positions for content slide / change on win. resize

		var w = '';
		if($.IEalert()==6){

			w = ($('#navigationSub a').length * (x+28));//ie6 scrollbar width

			for(var i=0;i<$('#navigationSub a').length;i++){
				slidepos[i] = i * (-x-28);
			}

		}else{
			w = $('#navigationSub a').length * x;

			for(var i=0;i<$('#navigationSub a').length;i++){
				slidepos[i] = i * -x;
			}

		}
		$('#slideInner').width(w);
		//console.log(slidepos);
		return slidepos;
}

$.setSubNaviPosCalls = function(){
	$('#navigationSub').find('a').each(function(i){
		$('#navigationSub a:eq('+i+')').bind('click',function(){
			if($('#page'+pageid+'Sub'+slideid+'_video').length>0){
				$.pauseMedia(pageid,slideid);
			}
			$('#slideInner:not(:animated)').animate({
				left: slidepos[i]
			},500,function(){
			slideid = i;
			//console.log('slideid = '+slideid);

			if(tier3id!=''){
				$.resetTier3Pages();
			}
			$.setActiveLinkColor();
			tier3flag = false;
			});
		});
	});
}

$.setSlideControlPosCalls = function(){
	//console.log('slideid = '+slideid);

	$('#controlLeft').bind('click',function(){
		if(slideid>0){
			if($('#page'+pageid+'Sub'+slideid+'_video').length>0){
				$.pauseMedia(pageid,slideid);
			}
			$('#slideInner:not(:animated)').animate({
				left:$('#slideInner').offset().left - slidepos[1]
			},500,function(){
			slideid--;
			//console.log('slideid = '+slideid);
			if(tier3id!=''){
				$.resetTier3Pages();
			}
			$.setActiveLinkColor();
			tier3flag = false;
			});
		}
	});
	$('#controlRight').bind('click',function(){
		if(slideid<slidepos.length-1){
			if($('#page'+pageid+'Sub'+slideid+'_video').length>0){
				$.pauseMedia(pageid,slideid);
			}
			$('#slideInner:not(:animated)').animate({
				left:$('#slideInner').offset().left + slidepos[1]
			},500,function(){
			slideid++;
			//console.log('slideid = '+slideid);
			if(tier3id!=''){
				$.resetTier3Pages();
			}
			$.setActiveLinkColor();
			tier3flag = false;
			});
		}
	});
}

$.checkForTier3Calls = function(){
	//console.log('# '+tier3active);
	var leftContentPos = $('.doubleContent:eq('+slideid+')').offset().left;
	//console.log('#page'+pageid+'Sub'+slideid+'Sub'+tier3id);
	$('.tier3page').hide();
	if(tier3flag == true){
		$('#page'+pageid+'Sub'+slideid+'Sub'+tier3id).css({
			left: -slidepos[slideid]
		});
		$('.tier3page:eq('+tier3id+')').show();
	}
	var subid = new Array();
	$('.page').find('.callTier3Page').each(function(i){
		var temp = $(this).attr('id').match(/[\d\.]+/g);
		tier3active = temp[1];
		subid[i] = $('.callTier3Page:eq('+i+')').parent().parent().parent().parent().parent().attr('id');
		$('.callTier3Page:eq('+i+')').bind('click',function(){
			if(tier3flag!=true){ //stop double clicking  
				tier3id = i;
				//console.log(pageid,slideid,tier3id);
				$('#page'+pageid+'Sub'+slideid+' .doubleContent').fadeOut(500);
				//$.updatePageId('#'+subid[i]);
				$('#'+subid[i]+'Sub'+i).css({
					left: -slidepos[slideid]
				});
				/*$('.tier3Content').css({
					left: leftContentPos
				});*/
				$('.callTier3Page').removeClass('active');
				$('.callTier3Page:eq('+i+')').addClass('active');
				tier3flag = true;
				$('.tier3page').fadeOut(600);
				$('#'+subid[i]+'Sub'+i).fadeIn(500);
				$.updatePageId('#'+subid[i]+'Sub'+i);
				tier3active=i;
				//console.log('# '+tier3active);
				//console.log('tier3id = '+tier3id);
				//console.log(tier3flag);
			}
		});
	});
	$('.tier3BackBtn').bind('click',function(){
		$('.tier3page').fadeOut(500,function(){
			tier3flag = false;
			$('#page'+pageid+'Sub'+slideid+' .doubleContent').fadeIn(500);
		});
		//console.log(tier3flag);
	});
	//console.log(subid);
}

$.resetTier3Pages = function(){ // fades out tier3 content 
	$('.callTier3Page').removeClass('active');
	tier3active='none';
	$('.tier3page').fadeOut(500);
	$('.doubleContent').fadeIn(500);
}
