$(document).ready(function() {
    if($(".overlayBG").length>0) $(".overlayBG").css('opacity', 0.6);
    if($(".whyWin .fields").length>0){
	$(".whyWin .fields INPUT").css('opacity', 0.7);
	$(".whyWin .fields TEXTAREA").css('opacity', 0.7);
	$(".whyWin .fields P.next INPUT").css('opacity', 1.0);
    }
    if($(".aboutYou").length>0){
	$(".whyWin .fields INPUT").css('opacity', 0.7);
	$(".whyWin .fields TEXTAREA").css('opacity', 0.7);
	$(".whyWin .fields P.next INPUT").css('opacity', 1.0);
    }
    // make external links(usually ads) open in a new page
    $("a[rel='ext']").each(function(){
	$(this).attr("target","_blank");
	$(this).attr("title","This link will open in a new window/tab.");
    });
    //===============
    // UPLOAD A VIDEO/PHOTO FORM
    if($(".uploadVideoPhoto").length>0){
	if(!$.browser.msie || ($.browser.msie && jQuery.browser.version!="6.0")){
	    $(".fileField").filestyle({
		    image: "/assets/images/buttons/browse.png",
		    imageheight : 32,
		    imagewidth : 136,
		    width : 250
	    });
	} else {
		$(".fileField").filestyleIE6({
			 image: "/assets/images/buttons/browse.gif",
			 imageheight : 32,
			 imagewidth : 136,
			 width : 250
		 });
	}
	/*$("input.fileField").clone().appendTo(".fileWrapper").attr("class","fileField2").attr("id","file2").css("left","180px");	
	$("input.fileField2").change(function(){
	    $("div.fileField").html($("input.fileField2").val());
	});
        */
	// check button
	$("input.agree").css({"opacity":"0","margin-top":"-20px"});
	$(".jsEnabled").click(function(){
	    if($("input.agree").attr("checked")==true){
		$("input.agree").attr("checked","");
		$(".jsEnabled").css("background","url(../assets/images/buttons/unchecked.png) 0 0 no-repeat");
	    } else {
		$("input.agree").attr("checked","checked");
		$(".jsEnabled").css("background","url(../assets/images/buttons/checked.png) 0 0 no-repeat");
	    }
	});
    }
    //=================================   
    // TELL ABOUT You FORM
    if($(".aboutYou").length>0){
	$("#country").height(0).width(0).css("overflow","hidden");
	$(".fakeSelect").show();
	$(".fakeSelect").find("LI.selected").click(function(){
	    var ul = $(this).parent();
	    if(ul.hasClass("open")){
		ul.removeClass("open");
		if($.browser.msie && jQuery.browser.version=="6.0") $(".parentEmail").css("visibility","visible");
	    }else{
		ul.addClass("open");
		if($.browser.msie && jQuery.browser.version=="6.0") $(".parentEmail").css("visibility","hidden");
	    }
	});
	$(".fakeSelect").find(".elements").click(function(){            
	    var ul = $(this).parent();
	    if(ul.hasClass("open")){
		ul.removeClass("open");
		if($.browser.msie && jQuery.browser.version=="6.0") $(".parentEmail").css("visibility","visible");
	    }else{
		ul.addClass("open");
		if($.browser.msie && jQuery.browser.version=="6.0") $(".parentEmail").css("visibility","hidden");
	    }
	    var clicked = $(this).html();
	    switch(clicked){
		case "Select":
		    $("#country").val("");
		    break;
		case "Select ":
		    $("#country").val("");
		    break;
		case "U.K":
		    $("#country").val("uk");
		    break;
		case "U.K ":
		    $("#country").val("uk");
		    break;
		case "Other":
		    $("#country").val("other");
		    break;
		case "Other ":
		    $("#country").val("other");
		    break;
	    }	    
	    ul.find("LI.selected").html($(this).html());
	});
        //$("#country").addClass("error");
        //$(".fakeSelect").addClass("errorFakeSelect");
        var selectValue="";
        switch($("#country").val()){
            case "":
                selectValue="Select";
                break;
            case "uk":
                selectValue="U.K";
                break;
            case "other":
                selectValue="Other";
                break;
        }
        $(".fakeSelect .selected").html(selectValue);
	$("form").submit(function(){
	    var submit = true;
	    if($("#firstName").val()==""){
		$("#firstName").addClass("error");
		$(".firstName LABEL").addClass("error");		
		submit = false;
	    } else {
		$("#firstName").removeClass("error");
		$(".firstName LABEL").removeClass("error");
	    }
	    if($("#surname").val()==""){
		$("#surname").addClass("error");
		$(".surname LABEL").addClass("error");		
		submit = false;
	    } else {
		$("#surname").removeClass("error");
		$(".surname LABEL").removeClass("error");
	    }
	    if($("#phone").val()==""){
		$("#phone").addClass("error");
		$(".phone LABEL").addClass("error");		
		submit = false;
	    } else {
		$("#phone").removeClass("error");
		$(".phone LABEL").removeClass("error");
	    }
	    if($("#address").val()==""){
		$("#address").addClass("error");
		$(".address LABEL").addClass("error");		
		submit = false;
	    } else {
		$("#address").removeClass("error");
		$(".address LABEL").removeClass("error");
	    }
	    $(".intro").removeClass("introError");
	    if($("#country").val()=="" || $("#country").val()=="other" || $("#country").val()==null){
		$("#country").addClass("error");
		$(".fakeSelect").addClass("errorFakeSelect");
		$(".country LABEL").addClass("error");
		 
		if($("#country").val()=="other") $(".intro").addClass("introError");
		submit = false;
	    } else {
		$("#country").removeClass("error");
		$(".fakeSelect").removeClass("errorFakeSelect");
		$(".country LABEL").removeClass("error");
	    }
	    if($("#email").val()==""){
		$("#email").addClass("error");
		$(".email LABEL").addClass("error");		
		submit = false;
	    } else {
		$("#email").removeClass("error");
		$(".email LABEL").removeClass("error");
	    }
	    if($("#parentEmail").val()==""){
		$("#parentEmail").addClass("error");
		$(".parentEmail LABEL").addClass("error");		
		submit = false;
	    } else {
		$("#parentEmail").removeClass("error");
		$(".parentEmail LABEL").removeClass("error");
	    }
	    if(!submit) $(".errorMessage").fadeIn();
	    return submit;
	});
	
    }
    //=================================
    
    $('#findSubmit').hover(
        function() {
            $(this).css('background-position', '0 -28px');
            $(this).css('cursor', 'pointer');
        },
        function() {
            $(this).css('background-position', '0 0');
        }
    );
    // Dynamically setting height of the callout boxes to the one that is highest - contains the most copy -  so that the links line up horizontally.
    var h = 0;	
    $('.fullBoxContent .thumbList LI').each(function(){																			 
        if ($(this).height() > h){
            h = $(this).height();		
        }
    });
    $('.fullBoxContent .thumbList LI').height(h);
    /*  CAROUSEL */
    if($('#carousel').length>0){
	$('#carousel').jcarousel();    
    /* CAROUSEL JSON */
        var page = 4;
        function mycarousel_itemAddCallback(carousel, first, last, data){
                var totalItems = $("#carousel").children().size();
                $.each(data,function(i,item){
                        var n = i+1;
                        $("<li></li>")
                                .attr("class","jcarousel-item jcarousel-item-horizontal jcarousel-item-"+(totalItems+n)+" jcarousel-item-"+(totalItems+n)+"-horizontal")
                                .attr("jcarouselindex",totalItems+n)
                                .html('<div class="thumbMask"><a href="'+item.href+'"></a></div><div class="preview"><a href="'+item.href+'"><img height="50" width="67" alt="" src="'+item.thumbnail+'"/></a></div>')
                                .appendTo("#carousel");
                        
                        carousel.add(totalItems+n, '<div class="thumbMask"><a href="'+item.href+'"></a></div><div class="preview"><a href="'+item.href+'"><img height="50" width="67" alt="" src="'+item.thumbnail+'"/></a></div>');
                        var nw = $("#carousel").width()+90;
                        $("#carousel").css("width",nw+"px");
                });
                carousel.size($("#carousel").children().size());
        };
        function loadMoreItems(carousel, state){
                $.ajax({
                        type: "GET",
                        url: "/ajax/watch-video.ajax.php?page="+page,
                        dataType: 'json',
                        error: function(){	
                                showError("Oops! Upload error! Please try again.");
                                return false;
                        },
                        success: function(data){
                                if (data!=""){								
                                        mycarousel_itemAddCallback(carousel, carousel.first, carousel.last, data);
                                }
                        }	
                });
                page++;
        }
        $('#carousel').jcarousel({			
                buttonNextCallback: loadMoreItems
        });
    }
	
    /*****  RATE THIS  ********/
    
    if($('#rateThis').length>0){
    function get_cookie ( cookie_name )
    {
        var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
        if ( results )
            return ( unescape ( results[2] ) );
        else
            return null;
    }	
    $('#rateThis').load('rate-this.php .rateThisContent', function(){																   
        var clicked = false;                                                                                                                       
        $('.rateThisContent h2').after(
            '<div id="rate">' +
                    '<ul class="png"></ul>' +
            '</div>'    
        );
        
        $('.rateThisContent input[type="radio"]').each(function() {
            var listTxt = $(this).attr('value');
            $('.rateThisContent ul').append(
                    '<li class="png"><span>' + listTxt + '</span></li>'
            );
            $(this).hide();
            $(this).next().hide();
        });
        $('.rateThisContent input[type="submit"]').hide();        
        // Grabbing the average rating from a cookie.
        var youR = get_cookie("ben_yourated");    
        if (youR){            
            var u = youR.split(',');            
            for (var i = 0; i < u.length; i++) {
                var u2 = u[i].split('=');
                //u2[0] = id of video or photo
                //u2[1] = rating
                if (u2[0] == id) {
                        $('#rateThis h2').css('background-image','url("/assets/images/text/you-rated-this.gif")');
                        $('#rateThis h2 span').html('You rated this!');
                        $('.rateThisContent ul').css('background-position', '0 -' + (u2[1] * 60) + 'px');
                        $('#rate').append('<div id="blockRate"></div>');
                        $('#blockRate').css('opacity', '0').show();	
                        $('#rating img').hide();
                }
            }            
        }        
        $('.rateThisContent ul li').hover(
            function() {
                var rating = $(this).text();
                $('.rateThisContent ul li').each(function(i) {
                    if ($(this).text() == rating) {
                        $(this).parent().css('background-position', '0 -' + ((i + 1) * 60) + 'px');
                    } 											  
                });
            },
            function() {
                if(!(clicked)) {
                    $(this).parent().css('background-position', '0 0');
                }
            }
        );        
        $('.rateThisContent ul li').click(function() {
            var post = 'rating= ' + $(this).text() + "&id=" + id;
            $.ajax({
                type: 'POST',
                url: '/ajax/rate-this.ajax.php',
                data: post,
                dataType: 'json',
                error: function(e){
                    alert('Unexpected response!'+e.responseText);
                    return false;
                },
                success: function(ratingData) {
                    $('.rateThisContent ul li').each(function(i) {
                        if (parseInt($(this).text()) == ratingData.rating) {
                            $(this).parent().css('background-position', '0 -' + ((i + 1) * 60) + 'px');
                            clicked = true;
                        } 											  
                    });
                    $('#rateThis h2').css('background-image','url("/assets/images/text/you-rated-this.gif")');
                    $('#rateThis h2 span').html('You rated this!');
                    $('#rate').append('<div id="blockRate"></div>');
                    $('#blockRate').css('opacity', '0').show();
                    $('#rating img').hide();
                    $('.currentRating p').text(ratingData.numVoters + " voters");
                    $('.currentStars span').fadeOut('fast', function() {
                        $(this).attr('id', 'avg' + (ratingData.avg).toString().replace(".", "-"));
                        $(this).fadeIn('fast');
                    });
                }
            });
            return false;
        });        
    });
    }
    /* OVERLAY */
    if($(".overlayHome").length>0){
	if(jQuery.cookie("ben10-hp-alert")!=1){
	    $(".bgOverlayHome").fadeIn(300,function(){$(".overlayHome").fadeIn(500);});
	    
	    $(".close A").click(function(){
		    $(".contentOverlay").fadeOut("fast",function(){$(".overlayBG").fadeOut("fast")});
		    return false;
	    });
	    $(".overlayBG").click(function(){
		    $(".contentOverlay").fadeOut("fast",function(){$(".overlayBG").fadeOut("fast")});
		    return false;
	    });
	    jQuery.cookie("ben10-hp-alert",1);
	}
    }
    if($(".openOverlay").length>0){
        $(".openOverlay").click(function(){
            var linkTo = $(this).attr("href");
            if($(".overlayContainer").length==0){
                // create overlay elements
                $("<div></div>")
                        .attr("class","overlayBg")
                        .css({"opacity":0.6,"display":"none"})
                        .prependTo("body");						
                $("<div></div>")
                        .attr("class","overlayContainer")	
                        .css({"display":"none"})
                        .prependTo("body");
                }
                $(".overlayBg").height($(document).height());
                // show overlay
                $(".overlayBg").fadeIn("fast",function(){$(".overlayContainer").fadeIn()});	
                // hide the overlay
                $(".overlayBg").click(function(){
                        $(".overlayContainer").fadeOut("fast",function(){$("overlayContainer").html("");$(".overlayBg").fadeOut("fast")});							
                });	
                $(".overlayContainer").load(linkTo+" .overlay", function(data){
                        window.scroll(0,0);
                        $(".overlayContainer").css("margin","0 0 0 -360px");
                        $("<div></div>")
                            .attr("class","close")
                            .css({"z-index":"999","float":"left","position":"absolute","right":"140px"})
                            .prependTo(".overlay");
                        $("<a href='#' class='png'></a>")
                            .css({"cursor":"pointer","z-index":"999","float":"left","position":"absolute"})
                            .prependTo(".close");
                        $(".close").click(function(){
                                $(".overlayContainer").fadeOut("fast",function(){$("overlayContainer").html("");$(".overlayBg").fadeOut("fast")});
                                return false;
                        });
                });
                return false;
        });
    }
    /*var position = 1;
    setInterval(function(){
        if (position == 1){
            $("#infoBar UL LI:last").fadeIn("slow");
            $("#infoBar UL LI:first").hide();
            position = 2
        }
        else {
            $("#infoBar UL LI:first").fadeIn("slow");
            $("#infoBar UL LI:last").hide();
            position = 1
        }        
    }, 10000); */
    /* CAMERA DETECTION */
    if($(".sendTrick").length>0){
    var flashvars = {};
        var params = {
          menu: "false",
          wmode: "transparent",        
          allowScriptAccess: "always",
          allowFullScreen: true
        };
        var attributes = {};                                            
        swfobject.embedSWF("/cameraDetector/CameraDetector.swf", "CameraDetector", "1", "1", "9.0.0","/flash/expressinstall.swf", flashvars, params, attributes);
        
        $(".detect").click(function(){
                jsTestMethod("trick");
                return false;
        });
    }
    if($(".submitButton").length>0){
        $(".submitButton").click(function() {
                var validFields = 0;            
                if ($('#file2').attr('value') == '') {
                        $('#file2').prev().addClass('error');
                } else {
                        $('#file2').prev().removeClass('error');
                        validFields++;	
                }            
                if ($('#agree').attr('checked') == false) {
                        $('#agree').next().addClass('error');	
                } else {
                        $('#agree').next().removeClass('error');
                        validFields++;	
                }            
                if (validFields == 2) {
                        $(this).attr('disabled', 'true');
                        $(this).css('cursor', 'default');
                        $(this).prev().html('Uploading, <strong>please wait</strong>...');
                        $('#upload-media').submit();
                }            
                //return false;
        });
    }
    if($("#flashLeft").length>0){
    var flashVars = {			
        videoURL        : "/video/diversity_spot_2tcm.flv" ,
        autoPlay        : false ,
        showControls    : true ,
        //loop            : true ,
        googlePageID    : "awards"
    };
    var params = { /*bgcolor:'#f4f4f4',*/ allowscriptaccess:'always' , allowfullscreen:'true' , wmode: 'transparent' };
    var attributes = { id: 'videoplayer' , name: 'videoplayer' };
    swfobject.embedSWF( "/flash/videoplayer.swf" , "flashcontent" , "312" , "180" , "9.0.0" , "/flash/expressinstall.swf" , flashVars , params , attributes );
    // ::::::::::::::::::::::::::::::   testing  JS -> Flash commands   ::::::::::::::::::::::::::::::::
    }
    if($("#flashMovie").length>0){
    var flashVars = {			
        videoURL        : "/video/alien_swarm_resized-16x9.flv" ,
        autoPlay        : false ,
        showControls    : true ,
        googlePageID    : "movie"
    };
    var params = { /*bgcolor:'#f4f4f4',*/ allowscriptaccess:'always' , allowfullscreen:'true' , wmode: 'transparent' };
    var attributes = { id: 'videoplayer' , name: 'videoplayer' };
    swfobject.embedSWF( "/flash/videoplayer.swf" , "flashcontent" , "485" , "308" , "9.0.0" , "/flash/expressinstall.swf" , flashVars , params , attributes );
    // ::::::::::::::::::::::::::::::   testing  JS -> Flash commands   ::::::::::::::::::::::::::::::::
    }
    if($(".picture:has(embed), .picture:has(object), .entry:has(embed), .entry:has(object)").length>0){
       $(".whyWin .imgMask, .aboutYou .imgMask, .thankYouTrick .imgMask").hide();
       $(".watchRate .entries .container .imgMask").hide();
       $(".watchRate .entries .container .entry").css("margin-top","0");
    }
    if($(".picture:has(embed), .picture:has(object), .entry:has(embed), .entry:has(object)").length>0){
       $(".whyWin .imgMask, .aboutYou .imgMask, .thankYouTrick .imgMask").hide();
       $(".watchRate .entries .container .imgMask").hide();
       $(".watchRate .entries .container .entry").css("margin-top","0");
    }
});
function getFlashMovie(movieName){
        var isIE = navigator.appName.indexOf("Microsoft") != -1;
        return (isIE) ? window[movieName] : document[movieName];
}
function jsTestMethod(page){
    switch(page){
           case "trick":
                   if(getFlashMovie("CameraDetector").hasWebcam()) self.location = "/capture.php";
                   else self.location = "/no-webcam.php";
                   break;
    }
}
/* FLASH FUNCTIONS */
function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    } else {
        return document[movieName];
    }
}
function isReady(){
    return true;
}

function playFLV(flvUrl) {
    thisMovie("videoplayer").playFLV(flvUrl);
}
function loadFLV(flvUrl) {
    thisMovie("videoplayer").loadFLV(flvUrl);
}

function stopFLV() {
    thisMovie("videoplayer").stopFLV();
}

function showProcessing() {
    thisMovie("videoplayer").showProcessing();
}

function showError(message) {
    thisMovie("videoplayer").showError(message);
}
// cookie management
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};