var PAGINATION_ENABLED = true;

//flash use this function
var openNewPage = function(page){
	window.open (page)
}

/* overlay class implementation
 * 
 * public functions:
 * init(): 
 * 		set anchors with rel="overlay" to be able to call overlay.
 * 
 * setOverlay(url):
 * 		this function should only be called from flash or other external entities that init() was not able to parse
 * 
 * setRedirect(url):
 * 		set a specific destination to take the user to if the overlay is closed
 * 		overriding the default of just closing the overlay
 * 
 * setSuccessURL(url):
 * 		set a specific destination to take the user if a form is submitted successfully
 */
var overlay = function() {
	var REDIRECT = false;
	var REFER_URL = "";
	var SUCCESS_URL = "";
	var FORM_OPTION = "";
	var DISABLE_FLASH = false;
	var FLASH_CONTAINER = "";
	
	

	var disableFlash = function(container){
		DISABLE_FLASH = true;
		FLASH_CONTAINER = container;
		container.hide();
	};
	
	//Private Functions
	var setRedirect = function (url){
		REFER_URL = url;
		SUCCESS_URL = url;
		REDIRECT = true;
	};
	var setSuccessURL = function (url) {
		if(url != ""){
			SUCCESS_URL = url;
		}
	};
	var destroyOverlay = function(){
		if(REDIRECT){
			if(typeof REFER_URL == 'function' ){
				REFER_URL();
			}
			else{
				location.href=REFER_URL;
			}
		}
		else{
			if(DISABLE_FLASH){
				FLASH_CONTAINER.show();
			}
			var fragment_id = $(".fragment").attr("id");
			if(fragment_id != "" && fragment_id){
				$(".overlaycontainer").removeClass(fragment_id);
			}
			
			/*remove flash communication object
			$(".flXHRhideSwf").remove();
			*/
			
		    $(".overlay").hide();
		    $(".overlaycontainer").hide();
		    $("body","html").css({height: "auto", width: "auto"});
		    $("html").css("overflow","");
			$("a[rel='close_overlay'],.overlay").unbind("click",destroyOverlay);
	
		    $("select").show();
		}
	    return false;
	};
	
	var cancelForm = function (){
		var postURL = $(".overlaycontainer input[name='_eventId_cancel']").parents("form").attr("action");
		$.post(postURL,{_eventId_cancel: "Cancel"});
		$("a[rel='close_overlay'],.overlay").unbind("click",cancelForm);
		destroyOverlay();
	}

	var processForm = function(selector) {
		$("a[rel='close_overlay']").one("click",destroyOverlay);
		$("#cancel-button").hide();
		$("a[rel='overlay']").click(function(){
			$(this).unbind('click');
			var url = $(this).attr("href");
			setOverlay(url);
			return false;
		});
		setExternalLinks();
		/*
		 * If there's a cancel-button, we have to make sure the action associated with that 
		 * button is called when overlay is closed
		 */ 
		if($("#cancel-button").length != 0){
			// $("a[rel='close_overlay'],.overlay").unbind("click",destroyOverlay);
			$("a[rel='close_overlay'],.overlay").one("click", cancelForm);
		}
		
		/*add footer text to all registration overlay
		if(($("#overlaycontent #accountForm").length !=0 )||
				($("#overlaycontent #screenNameForm").length !=0 )){
			//$("form#accountForm").after('<p id="copyright">&copy; 2009 The Coca-Cola Company.<br />"Fanta" and "Fantanas" are registered trademarks of The Coca-Cola Company.</p>');
		}
		*/
		
		//Form options
		var options = { 
			beforeSend: function() {
				$(".fragment").remove();
				/*$(".flXHRhideSwf").remove();*/
			},
			error: function (request, status, error){
				//how would we indicate something is wrong?
				//location.reload(true);
				cancelForm();
				if(typeof SUCCESS_URL == 'function' ){
					SUCCESS_URL();
				}
				else{
					location.href=SUCCESS_URL;
				}

			},
	        success: function(data) {
				var fragment =$(data).find(".fragment"); 
				if(fragment.html() != null){
		    		fragment.appendTo("#overlaycontent");
		    		processForm(".fragment form");
				}
				else{
					if(REDIRECT){
						if(typeof SUCCESS_URL == 'function' ){
							SUCCESS_URL();
						}
						else{
							location.href=SUCCESS_URL;
						}
					}
					else{
						location.reload(true);
					}
				}
	        }
		}
		if(FORM_OPTION == "crossdomain"){
			options.transport = "flXHRproxy";
		}
		$(selector).ajaxForm(options);
		return true;
	}

	var processContent = function(){
		//in IE "select" input shows through in overlay
		$("select").hide();
		//make sure "select" input in overlay is not hidden
		$(".fragment select").show();
	    
		//destroy overlay
		$("a[rel='close_overlay'],.overlay").bind("click",destroyOverlay);

		//set the class of the overlay container to a unique ID for styling background purposes
		var newClass = $(".fragment").attr("id");
		$(".overlaycontainer").addClass(newClass);

	    /* Calculate relative to content not whole window*/
	    var windowwidth = $(window).width();
	    var windowheight = $(document).height();

	    /* Calculate relative to content not whole window*/
	    //var containerHeight = $(window).height();
	    var containerHeight = $(".page").height();
	    
	    /*
	    $(".overlaycontainer").css({
	        "right": windowwidth / 2 - $(".overlaycontainer").width() / 2 + "px",
	        "top": containerHeight / 2 - $(".overlaycontainer").height() / 2 + "px"
	    });
	    */
	    
	    //phase 3 overlay
	    $(".overlaycontainer").css({
	        "right": windowwidth / 2 - $(".overlaycontainer").width() / 2 + "px",
	        "top": "90px"
	    });
	    
	    if(processForm(".fragment form")){
	    	$(".overlaycontainer").fadeIn("fast");
	    }
		setExternalLinks();

	}
	var setOverlay = function(location, postProcess){
		//activate overlay loader
	    $("body","html").css({height: "100%", width: "100%"});
	    var overlayHeight = $(document).height();
	    //make sure that the overlay covers correctly
	    overlayHeight = (overlayHeight > $(".overlay").height())? overlayHeight : $(".overlay").height(); 
	    $(".overlay").css({
	        "width": "100%",
	        "height": overlayHeight
	    });
		$(".overlay").show();
		
		//attach functions
		if(!postProcess){
			postProcess = processContent;
		}
		else{
			var newProcess = postProcess;
			postProcess = function (){
				processContent();
				newProcess();
			}
		}

	    $("#overlaycontent").load(location + " .fragment", postProcess);
	}
	var init = function(opt){ 
		//set get overlay
        $("a[rel='overlay']").click(function(){
			$(this).unbind('click');
			switch(opt){
				case "crossdomain":
					FORM_OPTION = "crossdomain";
					var url = $(this).attr("href");
					setOverlay(url);
			        return false;
			        break;
			    default:
			    	if($(this).hasClass("signinLink")){
						if($(this).attr("href").match("redirect")!=null){//click on your entry
//							$(this).attr("href",$(this).attr("href").replace("account/signin","contest/portal"));
						}
						else{
							$(this).attr("href","/contest/portal/?overlayAction=login");
						}
					}
					else if($(this).attr("id") == "registerLink"){
						$(this).attr("href","/contest/portal/?overlayAction=register");
					}
					else if($(this).attr("title") == "my account"){
						var myProtocol = window.parent.document.location.protocol
						if(myProtocol == "https:") {
							$(this).attr("href","/ssldocs/contest/portal/?overlayAction=myaccount");
						}
						else{
							$(this).attr("href","/contest/portal/?overlayAction=myaccount");
						}
					}
					else{
						var url = $(this).attr("href");
						setOverlay(url);
				        return false;
					
		        	}
			}		

	    });
	}

	
	return {
		//Public functions
		init: init ,
		setOverlay: setOverlay,
		setRedirect: setRedirect,
		setSuccessURL: setSuccessURL,
		disableFlash: disableFlash
	};
} ();

var displayOverlay2 = function(type, url, file){
	var resourcesURL = "/resources/images/downloads/"; 
	switch (type){
		case "wallpaper":
			overlay.disableFlash($("#flashcontent"));
			resourcesURL = resourcesURL + "wallpaper/";
			overlay.setOverlay("/fantana-fun/wallpaper/", function(){
				$("#preview-image").attr("src",resourcesURL+file);
			});
			break;
		case "screensaver":
			overlay.disableFlash($("#flashcontent"));
			resourcesURL = resourcesURL + "screensavers/"
			overlay.setOverlay("/fantana-fun/screensaver/", function(){
				$("#preview-image").attr("src",resourcesURL+url+".jpg");
				$("#screensaver-location").attr("href",resourcesURL+file);
				if(file.match("mac") != null){
					$("#pc").hide();
				}
				else{
					$("#mac").hide();
				}
			});
			break;
		case "theme":
			overlay.disableFlash($("#flashcontent"));
			overlay.setOverlay("/fantana-fun/theme/", function(){
				$('#copyButton').flash({  
				     swf: '/resources/media/copycode.swf',  
				     height: 66,
				     width: 157,
				     params: {
				         base: "/resources/media/",
				         scale: "noscale",
				         wmode: "transparent",
				         allowScriptAccess: "always"
				     }
				 }); 
		    });
			break;
		case "icon":
			overlay.disableFlash($("#flashcontent"));
			url = "/resources/images/downloads/";
			overlay.setOverlay("/fantana-fun/icon/");
			break;
		case "friend":
			overlay.setOverlay("/share/", function () {	$(".comment-input").keyup(charCount);} );
			break;
		case "login":
			window.location = ("/contest/portal/?overlayAction=login&redirect="+document.URL);
			break;
		case "getStarted":
			if($("#signed-in").length != 0){
				//if signed in
				switch(url){
					case "step3":
						window.location = "/contest/application/photo/";
						break;
					case "step4":
						window.location = "/contest/application/info/";
						break;
					default:
						window.location = "/contest/application/";
				}
			}
			else {
				window.location = ("/contest/portal/?overlayAction=register");
			}
			break;
		case "share-dancing":
			overlay.setOverlay("/share/", function () {	$(".comment-input").keyup(charCount);}, function(){
				$("#sharePageFormKey").val("dance");
				$("#shareUrl").val(url);
			});
			break;
		case "share-profile":
			overlay.setOverlay("/share/", function () {	
				$(".comment-input").keyup(charCount);
				$("#sharePageFormKey").val("contestantProfile");
				$("#shareUrl").val(document.URL);
			});
			break;
		case "reminder":
			overlay.setOverlay("/reminders/");
			break;
		default:
			alert("an error has occured: " + type + " url is " + url);
	}
	return false;
}



var sizedPopup = function(cur_href){
	window.open(cur_href,"Window","width=721, scrollbars=1");
}
var setExternalLinks = function (){
	/** External Links **/
	var setLink = function(){
		var cur_href = $(this).attr("href");
		if(cur_href.match(/terms\/$/) || cur_href.match(/privacy\/$/) || cur_href.match("/rules/") || cur_href.match(/sitemap\/$/)){
			sizedPopup(cur_href);
		}
		else{
			window.open(cur_href,"_blank");
		}
		return false;
	}
	$("a[rel='external']").click(setLink);

}
var styling = function (){
    //styling
    $("#sign-in li:first-child, #signed-in li:first-child").css("border-left", "0");
    if ($.browser.safari){
    	$("form#videoForm div.fakefile input").css("margin-top", "-30px");
    	$("#applicationPage h1").css({
    		'position': 'absolute',
    		'z-index' : '2'
    	});
    	$("#applicationPage #stepContainer").css("margin-top", "140px");
    }
    
    $("#infoForm input[type='text']").css("width", "176px");    
    $("#infoForm #extra-info input[type='text']").css("width", "222px"); 
    $("input[type=checkbox]").css("border","0px");	
    
    $("input[type=radio]").css("border","0px");
}

/* Disable animation */
function thisMovie(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    } 
	else {
		return document[movieName];
    }
}
function sendToActionScript() {
		thisMovie("flashMovie").sendToActionScript();
}

var charCount = function() {	
	var numberOfCharacters = 0;
	var maxNumberOfCharacters = 250;
	var text = $(this).val();		
	if(text != null && text.length != 0) {
		 if (text.length > maxNumberOfCharacters) {
			 var newText = text.substring(0, maxNumberOfCharacters);
		 	 $(this).val(newText);
		 } else {
			 // calculate the remaining characters  
				 numberOfCharacters = maxNumberOfCharacters - text.length;
			 }
		 $(this).next(".numchar").html(numberOfCharacters + " CHARACTERS LEFT");
	}
}

/*  PAGINATION */
//global settings
var ITEMS_PER_PAGE = 20;
var PARENT_PAGE = "";
function pageselectCallback(page_id, jq){
    var lo = (page_id * ITEMS_PER_PAGE);
    var hi = lo + ITEMS_PER_PAGE - 1;
    $("#comments ul>li").css("display", "block").filter(function(index){
        return index < lo || index > hi;
    }).css("display", "none");
}



$(document).ready(function(){
	//overlay.init("crossdomain");5
	overlay.init();
	setExternalLinks();
	initFileUploads();

    $("ul#nav li, ul#nav div, ul#nav a").hover(function(){
            $(this).children("div").show();
            $(this).children("div").focus();
            $("#important-reminders a").hide();

    }, function(){
        $(this).children("div").hide();
        $("#important-reminders a").show();
    });
    styling();
    
    //application why you wanna specific
    if(($("form#commentForm").length != 0) || ($("form#sharePageForm").length != 0)){
    		
    	charCount();
		//character count
    	$("#comment-input").keyup(charCount);
		
	}

    //reset password 
    if($("#resetPasswordForm").length != 0){
    	overlay.setOverlay(window.location);
    }

    //disable flash when clicked
	$("#nav a").bind("click",function(){
		try{
			sendToActionScript();
		}
		catch(err){
			return;
		}
	});
    
    /* PAGINATION */
    if($("#contestantProfile").length >0){
    	if(PAGINATION_ENABLED){
		    //display the 1st set of results
		    $("#comments ul>li").css("display", "block").filter(function(index){
		        return index < 0 || index > (ITEMS_PER_PAGE - 1);
		    }).css("display", "none");
		    
		    //get the total number of ads
		    var total = $("#comments ul>li").length;
		
		    // Create pagination element
		    $("#Pagination").pagination(total, {
		        num_edge_entries: 1,
		        num_display_entries: ITEMS_PER_PAGE,
		        link_to: "#comments",
		        callback: pageselectCallback
		    });
	
		    $(".current.prev, .current.next").css("display", "none");	
    	}
    	else{
    		$(".pagination").css("display","none");
    	}
	 
    }

});

