var debugStatus = true; // enable debugging to FF console

/* Feature - VIDEOs */
var YouTubeVideos = []; // holds youtube videos
var ProjectVideos =[]; // hold for project videos
var YouTubePlayerObject;
var ProjectsYouTubePlayerObject;
var TotalVideosLoaded = 0;
var vidLoadInterval;
var vidLoadPlayerInterval;
var CurrentActiveVideo = [];
var firstVideoClickDown = false;
var videoCarSet = false;
var requiredMajorVersion = 9;
var requiredMinorVersion = 9;
var requiredRevision = 0;


function onYouTubePlayerReady(playerId) {
	//alert("you tube loaded");
	
	
 
    
    setTimeout(function(){
    	YouTubePlayerObject = 	document.getElementById("myYouTubePlayerObject");	
		ProjectsYouTubePlayerObject = 	document.getElementById("ProjectVideosYouTubePlayerObject");	
			ProjectVideosWrapper.videoPlayerLoaded =true;
    },1000);
	
    
}

/* global functions  */
function bug(Dmsg) {
    try {
        if (debugStatus) {
            console.log(Dmsg);
        }
    } catch (er) {
    }
}



jQuery(document).ready(function () {

    site.nav();
    site.bind();
    site.bindButtons();
	site.tooltip();
	site.fileupload();
	site.videoHelp();
	site.formInputs();
	site.disabledHide();
	site.dropError();
	site.addError();

});


var site = {
    /* NEW_FUNCTION_NAME : function(){
		
    // custom code
	
    },
    */
	dropError : function(){
		
	   if($('.rowElemDrop').children().hasClass('error')) {
			 $('.jqTransformSelectWrapper').css('border', '1px solid #D2006D');
		}
	
    },
	addError : function(){
		
	   $('.rowElem').hasClass('error');
	   $('input').addClass('error');
	
    },
	disabledHide : function(){
		$('#content .jqtransform .form_help_wrap').css('display', 'block');	
		$('#content .jqtransform a.msg-popup').css('display', 'block');	
		$('#content .heading_panel_bot .trigger a').css('display', 'block');
    },
	tooltip: function(){
		
    $("a.link-i-msg").click(function(){
	$(".tooltip").fadeOut('fast');
        selectedHint = $(this).prev().find('input');
        $(this).next().fadeIn("slow");
        $(".close .closepop").focus();
        $(".hide_icon").css('visibility', 'visible');
        return false;
    }

	);
	
    $("a.closepop").click(function() {
        $(".tooltip").fadeOut("slow");
       selectedHint.focus();
        return false;

    });
	
	$("a.hide_next").click(function() {
        $(".hide_icon").css('visibility', 'hidden');
       selectedHint.focus();
        return false;

    });
	/*$("a.hide_next").click(function() {
        $(".hide_icon").css('zIndex', '0');
       selectedHint.focus();
        return false;

    });*/
	
	$("a.closepop").click(function() {
        $(".hide_icon").css('visibility', 'visible');
       selectedHint.focus();
        return false;

    });
	/*$("a.closepop").click(function() {
        $(".hide_icon").css('zIndex', '1');
       selectedHint.focus();
        return false;

    });*/
    },
	formInputs: function(){
		
    $(".jqtransform").jqTransform();
		 
		 $("input.file_2").filestyle({ 
          image: "/Resources/Upgrade/images/structure/browse.jpg",
          imageheight : 36,
          imagewidth : 103
          
      });
	
    },
	videoHelp: function(){
		
    		   	//Hide (Collapse) the toggle containers on load
	$(".panel_content").hide(); 

	//Switch the "Open" and "Close" state per click then slide up/down (depending on open/close state)
	$("div.trigger").click(function(){
		$(this).toggleClass("active").next().slideToggle("slow");
		return false; //Prevent the browser jump to the link anchor
	});
	
    },
	 fileupload: function(){
	 
			(function($) {
    
			$.fn.filestyle = function(options) {
						
				/* TODO: This should not override CSS. */
				var settings = {
					width : 105
				};
						
				if(options) {
					$.extend(settings, options);
				};
								
				return this.each(function() {
					
					var self = this;
					var wrapper = $("<div>")
									.css({
										"width": settings.imagewidth + "px",
										"height": settings.imageheight + "px",
										"background": "url(" + settings.image + ") 0 0 no-repeat",
										"background-position": "right",
										"display": "inline",
										"float": "left",
										"padding": "0 0 0 42px",
										"overflow": "hidden"
									});
									
					var filename = $('<input class="file" id="browse">')
									 .addClass($(self).attr("class"))
									 .css({
										 "display": "inline",
										 "width": "273px"
									 });

					$(self).before(filename);
					$(self).wrap(wrapper);

					$(self).css({
								"position": "relative",
								"height": settings.imageheight + "px",
								"width": settings.width + "px",
								"display": "inline",
								"cursor": "pointer",
								"opacity": "0.0"
							});

					if ($.browser.mozilla) {
						if (/Win/.test(navigator.platform)) {
							$(self).css("margin-left", "-142px");                    
						} else {
							$(self).css("margin-left", "-168px");                    
						};
					} else {
						$(self).css("margin-left", settings.imagewidth - settings.width + "px");                
					};

					$(self).bind("change", function() {
						filename.val($(self).val());
					});
			  
				});
				

			};
			
		})(jQuery);
    },
	/*tooltip: function () {

        jQuery('.link-i-msg').click(function () {
            jQuery('.tooltip').show();
        });
        jQuery('.tt-close').click(function () {
            jQuery('.tooltip').hide();
        });
    },*/

    nav: function () {
        /* Lava Lamp Navbar */
        jQuery("#navBar").navBar({
            fx: "backout",
            speed: 700,
            click: function (event, menuItem) {
            }
        });
    },
    bind: function () {

        jQuery('.login-link').click(function () {
            jQuery('.login-panel').show();
        });
        jQuery('.close-link').click(function () {
            jQuery('.login-panel').hide();
        });
    },
    bindButtons: function () {

        /* hover search for the button
        jQuery('.btn_apply, .btn_apply input'jQueryocus", function(){
        bug("hover");
        bug(jQuery(this).attr("type"))
        jQuery(this).addClass("btn-hover");
        });
        jQuery('.btn_apply, .btn_apply input').bind("mouseout blur", function(){
        bug("blur");
        bug(jQuery(this));
        jQuery(this).removeClass("btn-hover");
        });*/
        jQuery('.btn_search').hover(function () {
            jQuery('.btn_search input').css('cursor', 'pointer');
            jQuery('.btn_search').addClass("hover_search");
        }, function () {
            jQuery('.btn_search').removeClass("hover_search");
        });

        jQuery('.btn_search').focus(function () {
            jQuery('.btn_search input').css('cursor', 'pointer');
            jQuery('.btn_search').addClass("hover_search");
        }, function () {
            jQuery('.btn_search').removeClass("hover_search");
        });
		
        jQuery('.btn_login').hover(function () {
            jQuery('.btn_login input').css('cursor', 'pointer');
            jQuery('.btn_login').addClass("hover_login");
        }, function () {
            jQuery('.btn_login').removeClass("hover_login");
        });
        jQuery('.btn_login').focus(function () {
            jQuery('.btn_login input').css('cursor', 'pointer');
            jQuery('.btn_login').addClass("hover_login");
        }, function () {
            jQuery('.btn_login').removeClass("hover_login");
        });
        jQuery('.btn_apply').hover(function () {
            jQuery('.btn_apply input').css('cursor', 'pointer');
            jQuery('.btn_apply').addClass("hover_apply");
        }, function () {
            jQuery('.btn_apply').removeClass("hover_apply");
        });
        jQuery('.btn_apply').focus(function () {
            jQuery('.btn_apply input').css('cursor', 'pointer');
            jQuery('.btn_apply').addClass("hover_apply");
        }, function () {
            jQuery('.btn_apply').removeClass("hover_apply");
        });
        jQuery('.apply2').hover(function () {
            jQuery('.apply2 input').css('cursor', 'pointer');
            jQuery('.apply2').addClass("hover_apply2");
        }, function () {
            jQuery('.apply2').removeClass("hover_apply2");
        });
        jQuery('.apply2').focus(function () {
            jQuery('.apply2 input').css('cursor', 'pointer');
            jQuery('.apply2').addClass("hover_apply2");
        }, function () {
            jQuery('.apply2').removeClass("hover_apply2");
        });
		jQuery('.next_btn').hover(function () {
            jQuery('.next_btn input').css('cursor', 'pointer');
            jQuery('.next_btn').addClass("hover_next");
        }, function () {
            jQuery('.next_btn').removeClass("hover_next");
        });
			jQuery('.back_btn').hover(function () {
            jQuery('.back_btn input').css('cursor', 'pointer');
            jQuery('.back_btn').addClass("hover_back");
        }, function () {
            jQuery('.back_btn').removeClass("hover_back");
        });


    }
}





jQuery.fn.scrollableAddClones = function (addItems) {
    // grab scrollable plugin
    var scrollable;
    if (!(scrollable = jQuery(this).data('scrollable')) || !scrollable.getConf().circular)
        return;
    // grab scrollable elements and remember it's count
    var nodes = scrollable.getItems();
    var length = nodes.length;
    // grab class for the nodes
    var clonedClass = scrollable.getConf().clonedClass;
    // get wrap object to append the clones to
    var wrap = scrollable.getItemWrap();
    // fill as much nodes as needed for 500 pixels
    if (!addItems)
        addItems = Math.ceil(500 / nodes.eq(1).width());
    // create fake container to add the clones to (max 15 clones)
    var newNodesAppend = jQuery('<span />');
    for (var i = 1; i <= (addItems < 15 ? addItems : 15); i++)
        nodes.eq(i % length).clone().addClass(clonedClass).appendTo(newNodesAppend);
    // insert HTML
    newNodesAppend.children().appendTo(wrap);
}




function aJackLoad(args) {
    if (typeof args.url === "string") {
        url = args.url;
    }

    /* Get data from server   */
    jQuery.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        url: url,
        dataType: "jsonp",
        timeout: 20000,
        tryCount: 0,
        retryLimit: 3,
        success: function (data) {
            if (typeof args.CallFunction === "function") {
                args.CallFunction(data);
            } else {
                return data;
            }
        },
        error: function (x, e) {
            if (x.status == 0) {
                bug('You are offline!!\n Please Check Your Network.');
            } else if (x.status == 404) {
                bug('Requested URL not found.');
            } else if (x.status == 500) {
                bug('Internel Server Error.');
            } else if (e == 'parsererror') {
                bug('Error.\nParsing JSON Request failed.');
            } else if (e == 'timeout') {
                bug('Request Time out.');
            } else {
                bug('Unknow Error.\n' + x.responseText);
            }
        }
    });
}

/* class for video controls and playback */

var ProjectVideosWrapper = {
	 currentActiceProjectItem : 0,
	checkVideoLoadInterval :0,
	checkVideoLoadTimeout:0,
	autoRotateInterval:0,
	videoPlayerLoaded: false,
	itemClicked:false,
	currentActiceProjectObject: 0,
	
    init: function () {
		
	
		$.each(ProjectVideos,function(i,item){
					if(typeof(item.SupportVideo)==="object"){
					 item.SupportVideo.video_thumb = "http://i.ytimg.com/vi/" + item.SupportVideo.id + "/default.jpg";
					 }
		});

					jQuery("#ProjectVideosLarge").tmpl(ProjectVideos)
					.appendTo("#ProjectVideosLargeUL");
					video = ProjectVideos[0];

			
	
			// load in the first item video into the main video area
			   swfobject.embedSWF("http://www.youtube.com/e/" + video.id + "?enablejsapi=1&showinfo=0&playerapiid=ProjectsYouTubePlayerObject&autohide=1&autoplay=0",
				"projectsapiplayer", "440", "330", "8", null, null, {
				    allowScriptAccess: "always",
				    wmode:"transparent"
				}, {
				    id: "ProjectVideosYouTubePlayerObject"
				});

// bind a view event to the gallery thumb


	$('#viewGalThumLink').live('click',function(){
			$('#viewGalleryLink').trigger('click');
			
		});


			$('#ProjectVideosLargeUL li:first').addClass("current");	
			$('#ProjectVideosLargeUL li:last').addClass("last");			
			this.loadSupportingContent(video);
		
		$('#ProjectVideosLargeUL li').click(function() {
		ProjectVideosWrapper.itemClicked= true;
			ProjectVideosWrapper.loadProjectVideoBox(this);
			return false;
		});
		
	
		
			jQuery('#support,#celeb').hover(function() {
		ProjectVideosWrapper.itemClicked= true;

		});
		
		$('#panel-wrapper').hover(function() {
			ProjectVideosWrapper.itemClicked= true;
			
		});
		/*$('#ProjectVideosLargeUL li a').click(function() {
		location.href=$(this).attr("href");
			ProjectVideosWrapper.itemClicked= true;
			ProjectVideosWrapper.loadProjectVideoBox($(this).parent().parent().parent());
			
			return false;
		});	*/	
	
		ProjectVideosWrapper.autoRotateInterval = setInterval(function(){
			if(ProjectVideosWrapper.itemClicked){
				clearInterval(ProjectVideosWrapper.autoRotateInterval);
			}else{
				currentItem =$('#ProjectVideosLargeUL li.current').index()-1;
				totalItems = $('#ProjectVideosLargeUL li').length;
				goToItem  = currentItem++; 
				
				if(currentItem>totalItems){
					goToItem=0;
				}
		
				$('#ProjectVideosLargeUL li').each(function(i){
					if(i==(goToItem)){
						$(this).trigger("click");
						ProjectVideosWrapper.itemClicked=false;
					}
				});
			
			}
			
		
		},6000);
		
		
	},
	MatchVideotoIndex: function (videoID) {
        var returnVideo;
        jQuery.each(ProjectVideos, function (i, video) {
            if (video.id == videoID) {
                returnVideo = video;
            }
        });
        return returnVideo;
    },
	
	loadSupportingContent: function(item){

			jQuery('#ProjectVideos-video h3').text(item.title);
			jQuery('#ProjectVideoMoreLink').attr("href",item.url);
			jQuery('#support,#celeb').empty().hide();
		
		try {
			if(typeof item.SupportVideo === "object"){
		
				jQuery("#FeatureSupportVideoInfo").tmpl(item.SupportVideo).appendTo("#support");
			}
			if(typeof item.SupportGallery ==="object"){
			
		
		jQuery("#FeatureSupportGalleryInfo").tmpl(item.SupportGallery).appendTo("#support");
	
		  tb_init('a.thickbox');//pass where to apply thickbox
  		imgLoader = new Image();// preload image
		 imgLoader.src = tb_pathToImage;

		
		
		
			}
			jQuery("#FeatureCelebVideoInfo").tmpl(item.CelebVideo).appendTo("#celeb");
			
		}catch(e){ bug(e)}		
			
			jQuery('#support,#celeb').fadeIn('fast');

	},
	
	
	loadProjectGallery: function(){
		item  = ProjectVideosWrapper.currentActiceProjectObject;
		bug('loadProjectGallery');


			return false;
			}
	,
	

	

	loadProjectVideoBox: function(elm){
		$('#ProjectVideosLargeUL li.current').removeClass('current');
		$(elm).addClass('current');
		var id = $(elm).attr('data-project-video-id');
		
		
		if (this.currentActiceProjectItem != id) {
			this.currentActiceProjectItem = id;
			var item = ProjectVideosWrapper.MatchVideotoIndex(id);
			// now cue the video
			
			this.loadSupportingContent(item);
			
			ProjectVideosWrapper.checkVideoLoadInterval = setInterval(function(){
				if (ProjectVideosWrapper.videoPlayerLoaded) {
				
					clearInterval(ProjectVideosWrapper.checkVideoLoadInterval);
				
				if(ProjectVideosWrapper.checkVideoLoadTimeout >0){
					clearTimeout(ProjectVideosWrapper.checkVideoLoadTimeout);
				}
					ProjectVideosWrapper.checkVideoLoadTimeout = setTimeout(function(){
						clearInterval(ProjectVideosWrapper.checkVideoLoadTimeout);
						ProjectsYouTubePlayerObject.cueVideoById(item.id);
						
					},200);
				
					
					
				}
			}, 50, item);
			
			
			
			
		}
	}
	
}


/* YOU TUBE CAROUSEL */
var youtubeWrapper = {

    init: function () {

        // for each video in teh youtube video area load onto the page
        jQuery.each(YouTubeVideos, function (i, video) {

            if (!videoCarSet && video.area == "carousel") {
       
                swfobject.embedSWF("http://www.youtube.com/e/" + video.id + "?enablejsapi=1&showinfo=0&playerapiid=YouTubePlayerObject&autohide=1&autoplay=0",
				"ytapiplayer", "440", "330", "8", null, null, {
				    allowScriptAccess: "always"
				}, {
				    id: "myYouTubePlayerObject"
				});
                videoCarSet = true;
            }
            video.thumb = "http://i.ytimg.com/vi/" + video.id + "/hqdefault.jpg";
            youtubeWrapper.updatePage(video);
        });
        // see if all the video's in the carosel have loaded - it they have loaded then activate the scrollable stuff
        setTimeout(function () {
            jQuery("#browsable").scrollable({
                circular: true
            });
            jQuery('#browsable').scrollableAddClones();
        }, 1000);
        // if the youtube video player has loaded onto the page then load in the first video in the carasoul
        vidLoadPlayerInterval = setInterval(function () {
            if (typeof YouTubePlayerObject !== "undefined" && TotalVideosLoaded > 0) {

                jQuery("a.video:first").trigger("click");
                clearInterval(vidLoadPlayerInterval);
            }

        }, 200);
        jQuery(".trigger-video").live("click", function () {
            var videoID = jQuery(this).attr("data-video-id");
            youtubeWrapper.PlayVideoLoadInfo(videoID);

            if (firstVideoClickDown) {
                jQuery.scrollTo('#main-video', 800);
            } else {
                firstVideoClickDown = true;
            }

            return false;

        });
        jQuery('.like-total').live("click", function () {
            // function to send back to epi the like
            jQuery('.like-reg-msg').hide();

            if (typeof CurrentActiveVideo.likeRegistered === "undefined") {

                var locationPort = "";
                try {
                    if (window.location.port > 81) {
                        locationPort = ":" + window.location.port;
                    }
                } catch (Error) {
                }
                aJackLoad({
                    url: "http://" + document.domain + locationPort + "/AddVideoRating.aspx?videoID=" + CurrentActiveVideo.id,
                    CallFunction: youtubeWrapper.LikeRegistered,
                    ErrorFunction: youtubeWrapper.LikeNotRegistered
                });

            } else {
                jQuery('.like-reg-msg').text("Like already registered").fadeIn(700);
            }

            return false;
        });
    },
    loadYouTubeAPI: function (videoID) {

        aJackLoad({
            url: "http://gdata.youtube.com/feeds/api/videos/" + videoID + "?v=2&alt=json",
            CallFunction: youtubeWrapper.APIResponse
        });
    },
    APIResponse: function (data) {

        var item = youtubeWrapper.MatchVideotoIndex(data.entry.media$group.yt$videoid.$t);

        var addthisToLikeCount = 0;
        try {
            addthisToLikeCount = parseInt(data.entry.ytjQueryrating.numLikes);

        } catch (er) {
        }

        item.like = addthisToLikeCount + item.like;
        item.ytData = true;

        youtubeWrapper.setLike(item.like);

    },
    updatePage: function (item) {

        try {
            switch (item.area) {
                case "carousel":
                    jQuery("#TempVideoRoll").tmpl(item)
					.appendTo(".videoRoll");
                    TotalVideosLoaded++;
                    break;
                case "left":
                    jQuery("#TempVideoFeatured").tmpl(item)
					.appendTo(".feature-video-left");
                    break;

                case "right":
                    jQuery("#TempVideoFeatured").tmpl(item)
					.appendTo(".feature-video-right");
                    break;
            }
        } catch (e) {
        }
    },
    MatchVideotoIndex: function (videoID) {
        var returnVideo;

        jQuery.each(YouTubeVideos, function (i, video) {

            if (video.id == videoID) {

                returnVideo = video;
            }
        });
        return returnVideo;
    },
    setLike: function (likeCount) {

        try {
            if (likeCount > 0) {

                jQuery('.like-total a span').text('Like (' + likeCount + ')');
            }
        } catch (er) {
        }
    },
    PlayVideoLoadInfo: function (videoID) {

        jQuery('.like-total').removeClass("like-registered");
        jQuery('.like-reg-msg').hide();

        // find and return the array containing all the video information
        CurrentActiveVideo = youtubeWrapper.MatchVideotoIndex(videoID);

        // add a video-active class around the current item being played

        // tell the youtube video controler to play the video - pass in the youTube video ID
        YouTubePlayerObject.cueVideoById(CurrentActiveVideo.id);

        // update the intro text etc below the video using the data from the array
        jQuery(".like-this").empty();
        jQuery("#VideoText").tmpl(CurrentActiveVideo)
					.appendTo(".like-this");
        // if the YouTube API has said this video has rating then the array will contain a "item.like" - so we can use this to populate the "like button" text

        if (typeof CurrentActiveVideo.ytData === "undefined") {
            youtubeWrapper.loadYouTubeAPI(CurrentActiveVideo.id);
        } else {
            youtubeWrapper.setLike(CurrentActiveVideo.like);
        }

    },
    LikeRegistered: function () {
        jQuery('.like-total').addClass("like-registered");
        jQuery('.like-reg-msg').text("Like registered").fadeIn(700);
        CurrentActiveVideo.like = CurrentActiveVideo.like + 1;
        youtubeWrapper.setLike(CurrentActiveVideo.like);

        CurrentActiveVideo.likeRegistered = true;

        setTimeout(function () {
            jQuery('.like-reg-msg').fadeOut("slow");
        }, 2000);
    },
    LikeNotRegistered: function () {
        jQuery('.like-reg-msg').text("Error registering you like, please try again.").fadeIn(700);
        jQuery('.like-total').removeClass("like-registered");
    }
}

/* Hub button rollover 
	
		
	$(function() {
	
	$('#discover-think-big2 a').hover(function () {
		$('.image_on').fadeIn(600);
		$('.image_off').fadeOut(400);
	},
	function(){
		$('.image_on').fadeOut(600);
		$('.image_off').fadeIn(400);
	});
	});
	
	$(function() {
	
	$('#discover-think-big3 a').hover(function () {
		$('.image_on').fadeIn(600);
		$('.image_off').fadeOut(400);
	},
	function(){
		$('.image_on').fadeOut(600);
		$('.image_off').fadeIn(400);
	});
	});
	
	$(function() {
	
	$('#discover-think-big4 a').hover(function () {
		$('.image_on').fadeIn(600);
		$('.image_off').fadeOut(400);
	},
	function(){
		$('.image_on').fadeOut(600);
		$('.image_off').fadeIn(400);
	});
	});*/
	


