var eventSelect = {

    init: function() {
        var self = this;
        self.$eventSelect = $('#str-events-select');
        self.baseHref = document.getElementsByTagName('base')[0].href;
        self.$eventSelect.change(function(e) {
            if(self.$eventSelect.val() !== '') {
                window.location = self.baseHref + self.$eventSelect.val();
            }
        });
    }
}

var vidPlayer = {
    fPlayerSwf: 'swf/flowplayer.commercial-3.2.7.swf',
    baseHref : '',
    movie : '',
    poster : '',
    containerId : '',
    init : function(movie, poster, baseHref, containerId) {
        vidPlayer.baseHref = baseHref;
        vidPlayer.movie = movie;
        vidPlayer.poster = poster;
        vidPlayer.containerId = containerId;
        if(movie) {
            //console.log('found a video:' + vidPlayer.movie);
            vidPlayer.showPlayer();
        }
    },
    showPlayer: function() {
        $f(vidPlayer.containerId, vidPlayer.fPlayerSwf, {		// supply the configuration
            key: '#$c126df4e5b666352c33',
            clip : {			// Clip is an object, hence '{...}'
                autoPlay: false,
                autoBuffering: true,
                baseUrl: vidPlayer.baseHref
            },
            playlist: [vidPlayer.movie],

            onFinish: function() {		// set an event handler in the configuration
                console.log('end');
            }
        });
    },
    showPlayerMobile: function() {

    }
};

var sponsorLogos = {
    currentIndex: 0,
    logoPerRow: 2,
    waitTime: 5000,
    init: function() {
        $sponsorLogosArray = new Array();
        $sponsorLogosWrapper = $('.homeSponsorsBlock:eq(0)');
        $('a', $sponsorLogosWrapper).each(function(i) {
            $sponsorLogosArray.push($(this));
        });
        rows = Math.ceil($sponsorLogosArray.length / sponsorLogos.logoPerRow);
        $sponsorLogosWrapper.html('');
        for(x = 0; x < rows; x++) {
            $sponsorLogosWrapper.append('<div class="sponsors-row" id="sponsors-row-'+x+'"></div>');
            if(x == (rows-1)){
                sponsorLogos.drawLogos(rows);
            }
        }
    },
    drawLogos: function(rows) {
        rowCounter = 0;
        for(x = 0; x < $sponsorLogosArray.length; x++) {
            $('#sponsors-row-'+rowCounter, $sponsorLogosWrapper).append($sponsorLogosArray[x]);
            if(x % sponsorLogos.logoPerRow == (sponsorLogos.logoPerRow-1)) {
                rowCounter++;
            }
            if(x == ($sponsorLogosArray.length-1)) {
                $('.sponsors-row', $sponsorLogosWrapper).css({
                    opacity: 0
                });
                $('#sponsors-row-0', $sponsorLogosWrapper).css({
                    opacity: 1
                });
                setTimeout(function() {
                    sponsorLogos.showLogo(sponsorLogos.currentIndex);
                }, sponsorLogos.waitTime)
            }
        }
    },
    showLogo: function(currentIndex) {
        newIndex = ((currentIndex+1) == $('.sponsors-row', $sponsorLogosWrapper).length) ? 0 : currentIndex+1;
        $('.sponsors-row', $sponsorLogosWrapper).stop(true, true);
        $('#sponsors-row-'+currentIndex, $sponsorLogosWrapper).css({
            'z-index': 1
        });
        $('#sponsors-row-'+newIndex, $sponsorLogosWrapper).css({
            'z-index': 10
        }).animate({
            opacity: 1
        }, {
            duration: 1000,
            easing: "swing",
            complete: function() {
                $('#sponsors-row-'+currentIndex, $sponsorLogosWrapper).css({
                    opacity: 0
                });
                $('#sponsors-row-'+newIndex, $sponsorLogosWrapper).css({
                    'z-index' : 2
                });
                setTimeout(function() {
                    sponsorLogos.currentIndex = newIndex;
                    sponsorLogos.showLogo(sponsorLogos.currentIndex);
                }, sponsorLogos.waitTime)
            }
        })

    }
};

$(document).ready(function() {

    bVersion = getInternetExplorerVersion();

    if($('#str-events-select').length) { eventSelect.init(); }

    if(bVersion == -1) {
        VideoJS.setupAllWhenReady();
    } else {
        setTimeout('VideoJS.setupAllWhenReady()', 2000);
    }

    if($('.homeSponsorsBlock a').length > sponsorLogos.logoPerRow) {
        sponsorLogos.init();
    }

    /* if($('.video-js-box').length > 0) {
	$('.video-js-box').each(function(i) {
	    $('object', this).attr('id', 'flash_fallback_'+(i+1));
	    if((i+1) == $('.video-js-box').length) {
		VideoJS.setupAllWhenReady();
	    }
	}); 
	VideoJS.setupAllWhenReady();
    }*/

    
    // animateBoxes(bVersion);
    
    setTimeout(function() { 
        $('.contentBoxImageLink, .contentBoxImage').each(function() {
            if($(this).height() == 0) {
                imageHeight = $('img', this).height();
                if(imageHeight > 0) {
                    $(this).animate({
                        height: imageHeight
                    }, 550, "swing");
                }                
            }
        });
    }, 200);

    $('#headerSearch').focus(function() {
        if($(this).attr('value') == 'Enter Keywords') {
            $(this).attr('value', ''); 
        }
    });
    $('#headerSearch').blur(function() {
        if($(this).attr('value') == '') {
            $(this).attr('value', 'Enter Keywords'); 
        }
    });
    /* if(checkCookie() == false) {
    	setTimeout(function() {
                $('#subscribePopupWrapper').css({left : $('#page').offset().left});
                $(window).resize(function() {
                    $('#subscribePopupWrapper').css({left : $('#page').offset().left});
                });
                $('#subscribePopupWrapper').animate({bottom : 0}, 1000, 'easeOutExpo');
    	}, 1000);
    } */

    $('#subscribePopupClose, #subscribePopupOptOut').click(function(e) {
        e.preventDefault();
        $(window).unbind('resize');
        $('#subscribePopupWrapper').animate({
            bottom : -400
        }, 1000, 'easeOutExpo', function() {
            setCookie('subscriberPrompt', true, 365);
            $('#subscribePopupWrapper').remove();
        });
    });

    $('#subscribePopupForm').submit(function() {
        if(is_valid_email($('#email').val())) {
            setCookie('subscriberPrompt', true, 365);
            return true;
        } else {
            $('#subscribePopupForm').append('<p class="error">Please enter a valid address</p>');
            return false;
        }
    });
    
    
    
    //--------------- HOME CHANNEL SELECTOR ----------------//
    
    if($('#homeChannelSelector').length){
       
        
        var mask_width = 50;
        
        var gap = 0;
        
        var item_array = []
        
        var current_array = []
        
        var timer
        var interval_time = 8000;
        var current_index = 0
        var easing = 'easeInOutExpo';
        var time = 600;       
        
        $('.homeChannelImage').each(function(e){
            
            current_array.push({
                item:$(this), 
                id:e
            })
            
            $(this).click(function(){
                
                
                $('.homeChannelImage').each(function(i){
                    
                    if(i == e){
                    
                  
                        $('.navText').html('');
                        $('a', $(this)).clone().appendTo('.navText');
                 
                    }
                   
                    
                })
                
           
        
                
                
                
                var id = ((e-1) < 0)? (current_array.length-1): (e-1);
              
             
                
                var reordered_array = reorderArray(current_array, id);
               
               
              
                animateArray(reordered_array)
              
              
                clearInterval(timer)
                timer = setInterval ( showNextSlide, interval_time );
                  
               
               
               
            })
            
           
        
        })
        
        $('a.homeRight').click(function(e){
            showNextSlide()
            e.preventDefault();

        })
        
        $('a.homeLeft').click(function(e){
            showPrevSlide()
            e.preventDefault();

        })
        
     
        
        
        function animateArray(array){
            
            var new_array = resizeArray(array)


            var p = array.length
         
            for(var i=0;i<array.length; i++){

                $('img',array[i].item).stop(true).animate({
                    'left':-(new_array[i].offset)
                },time,easing)
                array[i].item.stop(true).animate({
                    'width':new_array[i].width, 
                    'left':new_array[i].x - mask_width
                },time, easing, function() {}); 
                
                array[i].item.css({
                    'z-index':p
                });
                
                
          
                
                p--
                
            }
           
           
        };

    
         
        
        
        function showNextSlide() {
            current_index ++
            current_index = (current_index > $('.homeChannelImage').length-1) ? 0 : current_index;
          
           
            $('.homeChannelImage').each(function(e){
               
                if(e == current_index){
                    $(this).trigger('click');
                }
           
            })
          
        } 
        function showPrevSlide() {
            current_index --
            current_index = (current_index < 0) ?  $('.homeChannelImage').length-1 : current_index;
          
           
            $('.homeChannelImage').each(function(e){
               
                if(e == current_index){
                    $(this).trigger('click');
                }
           
            })
          
        } 

        
        
        function initSelector(){
       
            var new_array = resizeArray(current_array)
           
            //console.log(new_array);
            for(var i=0;i<current_array.length; i++){
              
                item_array.push(current_array[i]);
               
            }
           
            $('.homeChannelImage').each(function(e){
               
                if(e == 0){
                    $(this).trigger('click');
                }
           
            })
           
        }
        
        
        function reorderArray(array, id){
         
            
            var end_array = []
            var begin_array = []
            var new_array = []
            
            for(var i=0;i<array.length;i++){
                
                if(i < id){
                    end_array.push(array[i])
                }else{
                    begin_array.push(array[i])
                }
                
            }
            new_array = begin_array.concat(end_array)
            
            return new_array
            
        }
        
        function resizeArray(array){ //returns array with desired width and x value
            
            var width_array = [];
            var x_array = [];
            var new_array = [];
            
            for(var i=0;i<array.length;i++){                
                var width = (i == 1) ? 480 : mask_width;
                width_array.push(width) ;
               
              
            }
            
            for(var i=0;i<array.length;i++){
                var x = (i == 1) ? mask_width : (width_array[i-1]+x_array[i-1]+gap)
                x = (i == 0) ? 0 : x 
                x_array.push(x); 
                var offset = (i == 1) ? 0 : 480/2;
                new_array.push({
                    width:width_array[i],
                    x:x, 
                    offset:offset
                });
               
               
            }
            
            
            
          
            
            return new_array
        }
        
        
        // animateArray(current_array);
        initSelector()
        
        
        
        
        
        if($('.countdownBox').length){
        
        
        
            dateFuture1 = new Date(2012,2,8,0,0,0);


            function GetCount(ddate){

                dateNow = new Date();	//grab current date
                amount = ddate.getTime() - dateNow.getTime();	//calc milliseconds between dates
                delete dateNow;

                days=0;
                hours=0;
                mins=0;
                secs=0;
                out="";

                amount = Math.floor(amount/1000);//kill the "milliseconds" so just secs

                days=Math.floor(amount/86400);//days
                amount=amount%86400;

                hours=Math.floor(amount/3600);//hours
                amount=amount%3600;

                mins=Math.floor(amount/60);//minutes
                amount=amount%60;

                secs=Math.floor(amount);//seconds
                    
                    
                $('.countdown-days h3').html(days);
                $('.countdown-hours h3').html(hours);
                $('.countdown-minutes h3').html(mins);
                $('.countdown-seconds h3').html(secs);
                    
                setTimeout(function(){
                    GetCount(ddate)
                }, 1000);

            }

            GetCount(dateFuture1)
        
        
        }
        
    }
    
    
    
   
    colorCycle()
     
     
    var flashMovie = document.getElementById('Gallery');
       
       
       
    if($('.newsletterBox #subscribeForm').length){
        $("form a.submit").click(function(e) {
            e.preventDefault()
       
                $(this).parents().filter("form").trigger("submit");
           
        });

    }


    // Manually perform placeholder functionality if browser does not support it
    var testElement = document.createElement('input');
    if(!('placeholder' in testElement)) {
        $('input.defaultSwapText').focus(defaultSwapTextClearCheck).blur(defaultSwapTextReplaceCheck).blur();
    }
});

function defaultSwapTextClearCheck() {
    if ($(this).val() == $(this).attr('placeholder')) {
        $(this).val('');
    }
}
function defaultSwapTextReplaceCheck() {
    if ($(this).val() == '') {
        $(this).val($(this).attr('placeholder'));
    }
}

var global_color = ''
 
 
function getColor(){
   return global_color;
}

 
function colorCycle(){
    
    //CHECK COOKIE 
    $('#page').removeClass('colors');return;
  
    
    var color_array = ['474da4','fdcf41','ee7f4b','a7d4ee'];
    
    
    
    if(getCookie('cookieColor')== ''){
        //init load of site
        var COLOR = 0
        setCookie('cookieColor',COLOR,7)
    }else{
       
        var COLOR = getCookie('cookieColor')
        COLOR++
        COLOR = (COLOR > color_array.length-1)? 0 : COLOR;
        setCookie('cookieColor',COLOR,7)
       
    }
    
    
    
    
    var color = "#" + color_array[COLOR];
    global_color = color_array[COLOR];
    
    //border-color
    var border_color_array = [
    '.headerSearchLinks',
    '#homeFlashContainer',
    '.contentBox', 
    '.imageBox',
    'h2.newsfeed',
    '.homeSponsorsWrapper h2',
    '.newsletterBox .newsletter',
    '.doubleColumn',
    '.whatsOnBox h2', 
    '.dateSelectBox h2',
    '#browseCpDateForm input',
    '.textBox h4',
    '.searchResultsHeader',
    '#searchResultsPagination'
    ]
    
    for(var i=0;i<border_color_array.length;i++){
        changeColor($(border_color_array[i]), "border-color",color);
    }
    
    
    //background-color

    var background_color_array = [
    '.subHeader',
    '.headerBlock',
    '.headerBlock h1',
    '.subHeader h1',
    '#pageFooter',
    '.clTitle',
    '.primaryNavigation ul li.selected a ',
    '.newsletterBox form a.submit',
    '#cpAlpha',
    '.quoteBlockContentWrapper',
    '#cpList .doubleColumn .cpEvent',
    '.tripleColumn',
    '#homeFlashContainer .navBg',
    '#homeFlashContainer .navBg',
    '#submit',
    'div.gallery div.thumbnail',
    'div.slideshow-wrapper'
    ]
    
    for(var i=0;i<background_color_array.length;i++){
        changeColor($(background_color_array[i]), "background-color",color);
    }
    
    //exception fixes
    
    $('.primaryNavigation ul li ul a').css('background-color', '#fff')
    
    
    //text-color
    
    
    //hover color
    
    //hoverColor($('.primaryNavigation ul li a'));
    
    
    //image color
    
    var box_image = 'images-v2/common/content-box-tab-'+COLOR+'.gif';
    $('img.contentBoxDecor').attr('src',box_image)
    //content-box-tab-1
    
    
    function hoverColor($element, $style, $color) {
    
        $element.mouseover(function(e){
            changeColor($(this),'background-color',color);
            
        });

        $element.mouseout(function(e){
        
            
            if(!$(this).parent().hasClass('selected')){
                changeColor($(this),'background-color','#fff')
            }
         
            if(!$(this).next().length && !$(this).parent().hasClass('homeNavItem')){
                changeColor($(this),'background-color','#fff')   
            }
            
        })

    }
    
    
    function changeColor($element,$style,$color){
       
        $element.css($style,$color);
        
    }
    
    
    
    
    
}

function animateBoxes(version) {
    if(version != 6 || version != 7) {
        $('.contentBoxImage').css({
            height: '0px', 
            overflow: 'hidden'
        });
        $('.contentBoxImageLink').css({
            height: '0px', 
            overflow: 'hidden'
        });
        $('.contentBox .contentBoxImageLink a img').each(function() {
            $(this).load(function() {
                imageHeight = $(this).height();
                $(this).parent().parent().animate({
                    height: imageHeight
                }, 550, "swing");
            });
        });
        $('.contentBox .contentBoxImage img').each(function() {
            $(this).load(function() {
                imageHeight = $(this).height();
                $(this).parent().animate({
                    height: imageHeight
                }, 550, "swing");
            });
        });
        $('.imageBox .contentBoxImageLink a img').each(function() {
            $(this).load(function() {
                imageHeight = $(this).height();
                $(this).parent().parent().animate({
                    height: imageHeight/*+13*/
                }, 550, "swing");
            });
        });
        $('.imageBox .contentBoxImage img').each(function() {
            $(this).load(function() {
                imageHeight = $(this).height();
                $(this).parent().animate({
                    height: imageHeight
                }, 550, "swing");
            });
        });
    }
}

function getInternetExplorerVersion() {
    var rv = -1;
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat( RegExp.$1 );
    }
    return rv;
}

function init() {
    $('a.popupLink').bind('click', function(e) {
        popupWindow($(this).attr('href'), $(this).attr('title').replace(/[^A-z]/ig, ''),'width=550, height=400, scrollbars');
        e.preventDefault();
    });
}

function popupWindow(url, name, attributes){
    var newWindow = window.open(url, name, attributes);
    newWindow.focus();
}
 
function setCookie(c_name,value,expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name+ "=" +escape(value)+
    ((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
} 

function getCookie(c_name) {
    if (document.cookie.length>0) {
        var c_start=document.cookie.indexOf(c_name + "=");
        if (c_start!=-1) {
            c_start=c_start + c_name.length+1;
            var c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) c_end=document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end));
        }
    }
    return "";
}

function checkCookie() {
    var subscribePrompt=getCookie('subscriberPrompt');
    if (subscribePrompt != null && subscribePrompt != '') {
        return true;
    } else { 
        return false;
    }
}

function is_valid_email (email)      {
    return /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email);
}
