/****************************************
 * CloudFlare
 * Global JavaScript
 ****************************************/

/*
// Start closure to prevent namespace conflicts
;(function($) {
*/

var cloudFlare = cloudFlare || {};

// make .js class available to assist css hiding for js features
$('html').addClass('js');

/*
 * Setup text input placeholder text (uses jquery.placeholder plugin)
 */
cloudFlare.setupAllTextInputPlaceholders = function() {
    $('input[type="text"], textarea').each(
	function() {
	    if ($(this).attr('placeholder')) {
		cloudFlare.setupTextInputPlaceholder(this);
	    }
	});

};

cloudFlare.setupTextInputPlaceholder = function(element) {
    $(element).placeholder({blankSubmit: true});
};

/*
 * Setup dropdownMenu controls
 */
cloudFlare.setupDropdownMenuControls = function() {
	$('.dropdownMenu').each(function() {
		// get elements
		var menu = $(this);
		var button = $('.dropdownMenu-button', menu);

		// button click handler
		button.live('click', function(event) {
			event.preventDefault();

			// prevent this menu from closing when it's clicked (see document.click below)
			event.stopPropagation();

			// close any other open menus
			$('.dropdownMenu-active').each(function() {
				var openMenu = $(this);
				if(openMenu.get(0) != menu.get(0)) {
					openMenu.removeClass('dropdownMenu-active');
				}
			});

			// unless this menu is disabled, toggle its active class
			if(!menu.hasClass('dropdownMenu-disabled')) {
				menu.toggleClass('dropdownMenu-active');
			}
		});

		// menu click handler
		$('ul', menu).live('click', function(event) {
			// prevent this menu from closing when it's clicked (see document.click below)
			event.stopPropagation();
		});
	});

	// close any open menus when anything that's not an open menu is clicked
	$(document).click(function() {
		$('.dropdownMenu').removeClass('dropdownMenu-active');
	});
};

/*
 * Setup text truncation
 */
cloudFlare.setupTextTruncation = function(context) {
    if(context == undefined) {
	context = $(document);
    }

    context.find('.truncated').each(
	function() {
	    var truncatable = $(this);
	    var targetWidth = truncatable.width();

	    truncatable.css('width', 'auto');

	    if(truncatable.width() <= targetWidth) {
		truncatable.removeClass('truncated');
		truncatable.removeAttr('title');
	    }
	    else {
		truncatable.removeClass('truncated');
		truncatable.addClass('didTruncate');
		truncatable.width(targetWidth);
		truncatable.textOverflow(); // make Firefox truncate with an ellipsis like other browsers
	    }
	});
};

/*
 * Setup page alerts
 */
cloudFlare.setupPageAlerts = function() {
	var alerts = $('#section-page-alerts');
	if(alerts.length > 0) {
		alerts.hide();
		alerts.fadeIn('normal');
	}
};

/*
 * Custom validation methods
 */
$.validator.addMethod("domain", function(value, element) {
	var domain = element.value;
	return this.optional(element) || /^(http:\/\/)?(((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))\.?$/i.test(domain);
}, "Please enter a valid domain name (e.g. mydomain.com).");
$.validator.classRuleSettings.domain = { domain: true };

/*
 * Function to initiate modal
 * Takes an id of the element to click to open the modal
 * Assumes that the link id follows the pattern #modal-{modal number}
 * Assumes the corresponding div follows the patters #modal-link-{modal number}
 */
cloudFlare.initiateModal = function(element) {
    var modalName = element.replace('modal-', '');
    var modal = $('#' + element);

    // dialog parameters
    var content = modal.dialog(
	{
	    modal: true,
	    autoOpen: false,
	    draggable: false,
	    resizable: false,
	    title: modal.find('h2:first').remove().text(),
	    width: 540
	});

    if (modalName == 'vimeo') {
	modal.dialog({ width: 690 });
	modal.dialog({position: ['center', 100]});
    }

    if (modal.hasClass('faq')) {
	modal.dialog({position: ['center', 100]});
    }

    modal.bind("dialogbeforeclose", function (event) {
	    // Check for which modals should get a confirmation before closing
	    if (modalName == 'automaticProcessFeedback') {
		// If there are any steps in progress ask user if they want to cancel
		if ($('.status-progress:visible').length > 0) {
		    if (modal.hasClass('nocancel')) {
			return false;
		    }
		    if (!confirm('Are you sure you want to stop the automatic process?')) {
			return false;
		    }
		}
	    }
	});

    // default closing
    modal.bind("dialogclose", function (event) {
	    // clear elements (for faq / feedback forms)
	    cloudFlare.modalClear(modal);
	});

    var dialog = content.parents('.ui-dialog');

    // translucent border
    if(!$.browser.msie) {
	dialog.prepend('<div class="ui-dialog-translucentBorder"></div>');
	dialog.css({
		       'background': 'transparent'
		   });
    }

    // Override appended CSS values for jQuery UI Dialog class
    dialog.css(
	{
	    'overflow': 'visible'
	});

    // trigger link : either id="modal-link-<modal>" or class="modal-link-<modal>"
    $('#modal-link-' + modalName + ', .modal-link-' + modalName).click(
	function(event) {
	    event.preventDefault();
	    modal.dialog('open');
	    // put the focus on the first visible input
	    modal.find(':input:visible:first').focus();
	});

    // Interaction of Feedback forms
    modal.find('input[value=No]').click(
	function() {
	    var feedbackComments = modal.find('.modal-feedbackForm-comments');
	    feedbackComments.fadeIn('fast');
	    feedbackComments.find('textarea').focus();
	});

    modal.find('input[value=Yes]').click(
	function() {
	    modal.find('.modal-feedbackForm-comments').fadeOut('fast');
	});

    modal.find('input[value=Submit feedback]').click(
	function () {
	   modal.find('.modal-feedbackForm').fadeOut(
	       'fast',
	       function() {
		   modal.find('.modal-feedbackSuccess').fadeIn('fast');
	       });
	});

  // Replace default close button click event handler with a custom one so that we can control the behavior better
    dialog.find('.ui-dialog-titlebar-close').unbind().click(
	function(event) {
	    event.preventDefault();
	    modal.dialog("close");
	});

    // close link(s)
    modal.find('.modal-closeLink').click(
	function(event) {
	    event.preventDefault();
	    modal.dialog("close");
	});

    // preload background image
    cloudFlare.preloadImages('/images/ui/ui-widget-overlay-background.png');
};

/*
 * Setup links on the modal Automatic process Feedback dialog
 * modal_diff_login() must be declared on the page
 */
cloudFlare.setupAutoFeedbackModal = function (modal) {
    modal.find(".try_again").live('click', function (event) {
	    event.preventDefault();

	    if (cloudFlare.pushIFrame) {
		cloudFlare.clearAutoFeedbackStep(modal.find('.modal-step'), 'modal-step-muted');
		$("#ajax_push_frame").html(cloudFlare.pushIFrame);
	    } else {
		// modal_close will take care of the clear
		modal.dialog("close");
	    }
	});

    modal.find(".different_account").live('click', function (event) {
	    event.preventDefault();
            modal.dialog("close");

	    modal_diff_login();
	});

    // default close for auto feedback modal
    modal.bind("dialogclose", function () {
     	    cloudFlare.abandonWarn = false;
     	    cloudFlare.clearAutoFeedbackStep(modal.find('.modal-step'), 'modal-step-muted');
     	    $("#dns-login-form")[0].reset();

	    modal_diff_login();
     	});
};

/*
 * Clear the different steps on the jquery object given in parameter
 */
cloudFlare.clearAutoFeedbackStep = function (jObj, className) {
    jObj.removeClass('modal-step-muted')
    .removeClass('modal-step-progress')
    .removeClass('modal-step-success')
    .removeClass('modal-step-error')
    .addClass(className);
};

/*
 * Convenience methods for setting automaticProcessFeedback modal dialog step statuses
 * e.g. options = {step: 1/2/3/4, status: 'muted/progress/success/error'}
 */
cloudFlare.setAutomaticProcessFeedbackStatus = function(options) {
	if(options.step == undefined || options.status == undefined) {
		return;
	}

	if (options.status == 'error') {
	    $('.modal-cancel').show();
	    cloudFlare.abandonWarn = false;
	}

	cloudFlare.clearAutoFeedbackStep($('#automaticProcessFeedback-step-' + options.step),
					 'modal-step-' + options.status);
}

cloudFlare.modalClear = function(modal) {
    modal.find('.modal-feedbackForm').show();
    modal.find('.modal-feedbackForm-comments').hide();
    modal.find('input[name=useful]').removeAttr("checked");
    modal.find('.modal-feedbackSuccess').hide();
    if (modal.hasClass('faq')) {
	modal.find('#faq-elts').empty().hide();
    }
};

/*
 * Preload images
 */
cloudFlare.preloadedImageCache = [];
// Arguments are image paths relative to the current page.
cloudFlare.preloadImages = function() {
	var args_len = arguments.length;
	for (var i = 0; i < args_len; i++) {
		var imageAlreadyLoaded = false;
		for(var j = 0; j < cloudFlare.preloadedImageCache.length; j++) {
			if(cloudFlare.preloadedImageCache[j].src.indexOf(arguments[i]) != -1) {
				imageAlreadyLoaded = true;
				break;
			}
		}
		if(!imageAlreadyLoaded) {
			var cacheImage = document.createElement('img');
			cacheImage.src = arguments[i];
			cloudFlare.preloadedImageCache.push(cacheImage);
		}
	}
};

/*
 * Check for old versions of Safari (< 4.0.5)
 */
cloudFlare.checkForOldSafari = function() {
	cloudFlare.oldSafari = false;
	if($.browser.safari) {
		// user agent string version number is like "531.22.7" (for 4.0.5)
		var versionComponents = ($.browser.version).split('.');
		var v0 = parseFloat(versionComponents[0]);
		var v1 = parseFloat(versionComponents[1]);
		if(v0 < 531) {
			cloudFlare.oldSafari = true; // version 3.x
		}
		else if(v0 == 531 && v1 < 22) {
			cloudFlare.oldSafari = true; // version 4.0.4 and lower
		}
	}
};

/* Display one or several faq elements
 *  lang: string representing the lang (e.g: 'en_US')
 *  topics: array of topics id
 */
cloudFlare.faq = function(lang, topics) {
    $(".faq-loading").show();

    $.ajax({
	       url: '/ajax/faq.html',
	       cache: true,
	       data: { 'hl': lang, 'q': topics },
	       dataType: 'json',
	       success: function(response) {
		   var faqList = $('#faq-elts');
		   $(response).each(
		       function() {
			   var faqElt = $('#faq-elt-template').clone();
			   faqElt.addClass('faq-elt').removeClass("hidden");
			   faqElt.children('#modal-faq-question').append(this.question);
			   faqElt.children('#modal-faq-answer').append(this.answer);
			   faqList.append(faqElt);
		       });
		   $(".faq-loading").fadeOut('slow', function () {
			   faqList.fadeIn('normal');
		       });
	       }
	   });
};

/* Load a vimeo video
 */
cloudFlare.vimeo = function(vimeo_id) {
    var element_id = "vimeo_video";

    var flashvars = {
	"clip_id"	: vimeo_id,
	"show_title"	: 0,
	"show_byline"	: 0,
	"show_portrait"	: 0,
	"color"		: "e67300",
	"fullscreen"	: 1,
	"autoplay"	: 1,
	"js_api"	: 1,
	"js_onLoad"	: "cloudFlare.vimeo_onLoad",
	"js_swf_id"	: element_id
    };

    var params = {
	"allowscriptaccess"	: "always",
	"allowfullscreen"	: "true"
    };

    var attributes = {};

    swfobject.embedSWF("http://vimeo.com/moogaloop.swf", element_id, "640", "400", "9.0.0","flash/expressInstall.swf", flashvars, params, attributes);

    var modal = $("#" + element_id).parents(".modal");

    modal.bind("dialogclose", function() {
        var moogaloop = document.getElementById(element_id);
        moogaloop.api_unload();
    });
};


cloudFlare.vimeo_onLoad = function (element_id) {
    var moogaloop = document.getElementById(element_id);

    moogaloop.api_addEventListener("onFinish", "cloudFlare.vimeo_onFinish");
};

cloudFlare.vimeo_onFinish = function (element_id) {
    var modal = $("#" + element_id).parents(".modal");

    modal.dialog("close");
};



cloudFlare.setupNavigateAway = function() {
    window.onbeforeunload = function() {

	if (cloudFlare.loadingMessage) {
	    setTimeout(function() {
		    // show Loading
		    $(".message-area").show();

		    // change the message after 5 sec
		    setTimeout(function() {
			    $("#message-area-text").html("Still Working... Please be patient.");
			},
			5000);
		},
		500);
	}

	if (cloudFlare.abandonWarn) {
	    return "We're in the middle of a transaction. We recommend that you let us finish. Leaving now may result in data loss.";
	}
    };
};

/* Potential slow links/buttons are deactivated after the first click,
 * and the loading message box will show if the event is slow
 *
 * NOTE: this shouldn't be used on a submit which uses the validate plugin.
 */
cloudFlare.setupSlowLinks = function() {
    $('.slow').bind("click", function(event) {
	    if ($(this).hasClass("disabled")) {
		event.preventDefault();
	    } else {
		cloudFlare.loadingMessage = true;
		($(this).addClass("disabled"));
	    }
	});
};

cloudFlare.setupDatePicker = function () {
    $('.date-picker').datepicker({
	dateFormat: 'yy-mm-dd'
		});
}

// Perform initial setup tasks when DOM is ready
$(document).ready(
    function() {
	// default value for intial form fields
	cloudFlare.setupAllTextInputPlaceholders();

	// setup dropdown controls
	cloudFlare.setupDropdownMenuControls();

	// setup text truncation for firefox
	cloudFlare.setupTextTruncation();

	// setup page alerts
	cloudFlare.setupPageAlerts();

	// setup navigate away
	cloudFlare.abandonWarn = false;
	cloudFlare.loadingMessage = false;
	cloudFlare.setupNavigateAway();

	// setup potentially slow links
	cloudFlare.setupSlowLinks();

	// setup date picker
	cloudFlare.setupDatePicker();

	// initiate modals
	$('.modal').each(
	    function() {
		cloudFlare.initiateModal($(this).attr('id'));
	    });

	// check for old safari
	cloudFlare.checkForOldSafari();
});

/*
// End closure
})(jQuery);
*/
