var config = {
    sensitivity: 2, 		// number = sensitivity threshold (must be 1 or higher)
    interval: 100, 		    // number = milliseconds for onMouseOver polling interval
    over: megaHoverOver, 	// function = onMouseOver callback (REQUIRED)
    timeout: 200, 			// number = milliseconds delay before onMouseOut
    out: megaHoverOut 		// function = onMouseOut callback (REQUIRED)
};

$(document).ready(function() {
    // newsletter input field default value
    $("#NewsLetterSubscriptionEmail").DefaultValue("Subscribe to newsletter");

    // fix png images for ie
    //$.ifixpng('./assets/images/pixel.gif');
    //$('img[src$=.png]').ifixpng();

    // setup main menu
    $("ul#mainMenu li .subMenuHolder").css({ 'opacity': '0' }); // Fade sub nav to 0 opacity on default
    $("ul#mainMenu li").hoverIntent(config); 				 // Trigger Hover intent with custom configurations




	$(".carouselbox").jCarouselLite({
        btnNext: ".next",
        btnPrev: ".prev",
	auto: 3000,
    	speed: 1000
    });




    // create news ticker on homepage
     $('#news').innerfade({ animationtype: 'fade', speed: 750, timeout: 2000, type: 'sequence', containerheight: '80px' });

    // handle tooltips in carousel
    $.carouselToolTips = function() {
        var newTip = $('<div>').attr('id', 'toolTip');
        newTip.append($('<div>').addClass('toolTipContent'));
        $('body').prepend(newTip.hide());

        var tip = $('#toolTip'); var link;
        var tipContent = $('#toolTip .toolTipContent');

        $(".tip_trigger").hover(function() {
            link = $(this).find('a:first');
            if (link.length > 0) link = link[0];
            else link = this;
            tipContent.text(link.title);
            link.title = "";
            tip.show();
        }, function() {
            link.title = tipContent.text();
            tip.hide();
        }).mousemove(function(e) {
            var tipWidth = tip.width();     // Find width of tooltip
            var tipHeight = tip.height();   // Find height of tooltip
            var mousex = e.pageX - (tipWidth / 2);   // Get X coodrinates
            var mousey = e.pageY - (tipHeight + 10); // Get Y coordinates
            tip.css({ "top": mousey, "left": mousex });
        });
    };
    $.carouselToolTips();

    if ($("#flashworldmap").length > 0) {
        $('#flashworldmap').flash('assets/swf/FlashWorldMap.swf');
    }
});

function megaHoverOver(){
    $(this).find(".subMenuHolder").stop().fadeTo('fast', 1).show(); //Find sub and fade it in
    (function($) {
		//Function to calculate total width of all ul's
		jQuery.fn.calcSubWidth = function() {
			rowWidth = 0;
			//Calculate row
			$(this).find("div ul").each(function() { //for each ul...
				rowWidth += $(this).outerWidth(); //Add each ul's width together
			});
		};
    })(jQuery); 
	
    (function($) {
		//Function to calculate position of submenu
		jQuery.fn.calcSubPosition = function() {
			currentMenuItem = $(this);
			positionTop = (currentMenuItem.position().top + $(this).outerHeight()) + 2;
			positionLeft = currentMenuItem.position().left;
			//if(currentMenuItem.hasClass("active")) positionLeft -= 2;
		};
    })(jQuery); 
	
	var currentSubMenu = $(this).find(".subMenuHolder");
	$(this).calcSubPosition();
	currentSubMenu.css({'top' : positionTop}).css({'left' : positionLeft});
	
	if ( $(this).find(".row").length > 0 ) { //If row exists...
		var biggestRow = 0;	
		$(this).find(".row").each(function() { //for each row...
			$(this).calcSubWidth(); //Call function to calculate width of all ul's
			//Find biggest row
			if(rowWidth > biggestRow) {
				biggestRow = rowWidth;
			}
		});
		currentSubMenu.css({'width' : biggestRow}); //Set width
		$(this).find(".row:last").css({'margin':'0'}); //Kill last row's margin
	} else { //If row does not exist...
		$(this).calcSubWidth(); //Call function to calculate width of all ul's
		currentSubMenu.css({'width' : rowWidth}); //Set Width
	}
}

function megaHoverOut(){
	$(this).find(".subMenuHolder").stop().fadeTo('fast', 0, function() { //Fade to 0 opactiy
		$(this).hide(); //after fading, hide it
	});
}

/**********************************************************************************************************************/
/** NEWSLETTER SUBSCRIPTION *******************************************************************************************/
/**********************************************************************************************************************/

function SendNewsletterSubscribtion() {
    var emailInput = $("#NewsLetterSubscriptionEmail").val();
    var params = { email: emailInput };
    
    $.ajax({
        type: "POST",
        url: getBaseURL() + "NewsletterSubscription.aspx/SendNewsletterSubscribtion",
        data: $.toJSON(params),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSubscribtionSucceeded,
        error: OnSubscribtionFailed
    });
};

function OnSubscribtionSucceeded(data, textStatus, XMLHttpRequest) {
    if ($("#submitNewsLetter p.error").length > 0) {
        $("#submitNewsLetter p.error").remove();
    }
    if ($("#submitNewsLetter p.success").length > 0) {
        $("#submitNewsLetter p.success").remove();
    }
    $("<p>").attr("class", "success").text("Thank you!").appendTo("#submitNewsLetter");
}

function OnSubscribtionFailed(XMLHttpRequest, textStatus, errorThrown) {
    var errorMessage = $.parseJSON(XMLHttpRequest.responseText);
    if ($("#submitNewsLetter p.error").length == 0) {
        $("<p>").attr("class", "error").text(errorMessage.Message).appendTo("#submitNewsLetter");
    }
}

function getBaseURL() {
    var url = location.href;  // entire url including querystring - also: window.location.href;
    var baseURL = url.substring(0, url.indexOf('/', 14));

    if (baseURL.indexOf('http://localhost') != -1) {
        // Base Url for localhost
        var url = location.href;  // window.location.href;
        var pathname = location.pathname;  // window.location.pathname;
        var index1 = url.indexOf(pathname);
        var index2 = url.indexOf("/", index1 + 1);
        var baseLocalUrl = url.substr(0, index2);

        return baseLocalUrl + "/";
    }
    else {
        // Root Url for domain name
        return baseURL + "/";
    }
}

