$(document).ready(function () {
    $("#Facebook, #Twitter").hover(function () {
        $(this).prev().show();
    }, function () {
        $(this).prev().hide();
    });


    $(".sectionMenu_Option").hover(function () {
        $(this).children(":first").show();
    }, function () {
        $(this).children(":first").hide();
    });

    $(".productBox").hover(function () {
        $(this).children(":first").show();
    }, function () {
        $(this).children(":first").hide();
    });

    $(".menu_option").hover(function () {
        $(this).find(".menu_subOption").parent(":first").show();
    }, function () {
        $(this).find(".menu_subOption").parent(":first").hide();
    });

    $(".rolloverMenu").hover(function () {
        $(this).children(":eq(0)").hide();
        $(this).children(":eq(1)").show();
    }, function () {
        $(this).children(":eq(1)").hide();
        $(this).children(":eq(0)").show();
    });

});
	
function ShowMenu(menu){
	$("#menu_" + menu).show();
	$("#menuTitle_" + menu).css("position","relative").css("z-index","50");
}

function HideMenu(menu){
	$("#menu_" + menu).hide();
}

function FadeOut(obj){
	obj.fadeTo('fast', 1);
	$(".categories_Box").not(obj).fadeTo('fast', 0.2, function(){
		//$(obj).removeAttr('filter');
	});
}

function FadeIn(){
	$(".categories_Box").fadeTo('fast', 1, function(){
		//$(obj).removeAttr('filter');
	});
}

function GetTweets(query){
	//var twitterPage = 1 + Math.floor (Math.random () * 10);
    var twitterQuery = encodeURIComponent (query);
	var twitterResults = 30;
	var requestUrl = "http://search.twitter.com/search.json?q=@query&rpp=@results&callback=?".
            replace (/@query/g, twitterQuery).
            replace (/@results/g, twitterResults);
	$.getJSON (requestUrl, function (data){
		var tweets = "";
		var totalTweets = data.results.length;
		for (i=totalTweets-1; i>=0; i--)
		{
			var tweet = data.results [i];
			var time = prettyDate(tweet.created_at);
			text = tweet.text;
			text = text.replace(/(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim, "<a href='$1' target='_blank' class='linkSmall'>$1</a>");
			text = text.replace(/(^|[^\/])(www\.[\S]+(\b|$))/gim, "$1<a href='http://$2' target='_blank' class='linkSmall'>$2</a>");
			text = text.replace(/(^|\s)@(\w+)/g, "$1<a target='_blank' href='http://www.twitter.com/$2' class='linkSmall'>@$2</a>");
			text = text.replace(/(^|\s)#(\w+)/g, "$1<a target='_blank' href='http://twitter.com/#!/search/%23$2' class='linkSmall'>#$2</a>");
			currentTweet = CreateTweet(tweet.profile_image_url, tweet.from_user, text, time);
			tweets = tweets + currentTweet;
		};
		$("#Tweets").html (tweets);
		
		var $news = $('#Tweets');//we'll re use it a lot, so better save it to a var.
		$news.serialScroll({
			items:'.twContainer',
			duration:1500,
			force:true,
			axis:'y',
			easing:'swing',
			cycle: true,
			constant: true,
			lazy:false, // NOTE: it's set to true, meaning you can add/remove/reorder items and the changes are taken into account.
			interval:15000, // yeah! I now added auto-scrolling
			step:3 // scroll 2 news each time
		});	
    });
}


function CreateTweet(avatar, username, message, time) {
    var tweetBox = $("#tweetTemplate").clone();
    tweetBox.find("img[class='twImage']").attr("src",avatar);
	tweetBox.find("div[class='twText']").html(message);
	tweetBox.find("div[class='twTime']").html(time);
	tweetBox = tweetBox.html().replace(/@@UserName@@/g, username);
    return tweetBox;
}


function prettyDate(time){
	var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
		diff = (((new Date()).getTime() - date.getTime()) / 1000),
		day_diff = Math.floor(diff / 86400);
			
	if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
		return;
			
	return day_diff == 0 && (
			diff < 60 && "Hace menos de 1 minuto" ||
			diff < 120 && "Hace 1 minuto" ||
			diff < 3600 && "Hace " + Math.floor( diff / 60 ) + " minutos" ||
			diff < 7200 && "Hace 1 hora" ||
			diff < 86400 && "Hace " +  Math.floor( diff / 3600 ) + " horas") ||
		day_diff == 1 && "Ayer" ||
		day_diff < 7 && "Hace " + day_diff + " días" ||
		day_diff < 31 && "Hace " + Math.ceil( day_diff / 7 ) + " semanas";
}

// If jQuery is included in the page, adds a jQuery plugin to handle it as well
if ( typeof jQuery != "undefined" )
	jQuery.fn.prettyDate = function(){
		return this.each(function(){
			var date = prettyDate(this.title);
			if ( date )
				jQuery(this).text( date );
		});
	};

function AnimateBanner() {
	var objs = $(".bannerImg_Animated");
	objs.each(function(){
		$(this).animate({
			opacity:"toggle"
			}, {
			duration: 500,
			queue: "global"
		});
		$(this).animate({
			opacity:"toggle"
			}, {
			preDelay: 2000,
			duration: 200,
			queue: "global"
		});
	});
	
	$("#dummyObj").animate({
		opacity: 1
		}, { 
		duration: 1,
		queue: "global",
		complete: function() {
			AnimateBanner();
	}});
}

function ShowMore(obj){
	$("#" + obj).slideToggle();
}

function ShowProduct(prod) {
    SwitchView(prod);
}

function SwitchView(prod) {
    $("div[id*='Tick']").hide();
    $("#Tick" + prod).show();
    $(".product_box").hide();
    $("#" + prod).fadeIn();
    //JumpTo("BrandsBox");
}

function JumpTo(target) {
    $('html,body').animate(
       {
           //get top-position of target-element and set it as scroll target
           scrollTop: $("#" + target).offset().top
           //scrolldelay: 2 seconds
       }, 400, function () {
           //attach the hash (#jumptarget) to the pageurl
           location.hash = target;
    });
}


function GenerateCountryList() {
    var countryList = [
        {
            "countryName": "Argentina",
            "countryCode": "AR"
        },
        {
            "countryName": "Bermuda",
            "countryCode": "BM"
        },
        {
            "countryName": "Bolivia",
            "countryCode": "BO"
        },
        {
            "countryName": "Cayman Islands",
            "countryCode": "KY"
        },
        {
            "countryName": "Chile",
            "countryCode": "CL"
        },
        {
            "countryName": "Colombia",
            "countryCode": "CO"
        },
        {
            "countryName": "Costa Rica",
            "countryCode": "CR"
        },
        {
            "countryName": "Ecuador",
            "countryCode": "EC"
        },
        {
            "countryName": "Guatemala",
            "countryCode": "GT"
        },
        {
            "countryName": "Honduras",
            "countryCode": "HN"
        },
        {
            "countryName": "Nicaragua",
            "countryCode": "NI"
        },
        {
            "countryName": "Panamá",
            "countryCode": "PA"
        },
        {
            "countryName": "Paraguay",
            "countryCode": "PY"
        },
        {
            "countryName": "Perú",
            "countryCode": "PE"
        },
        {
            "countryName": "Puerto Rico",
            "countryCode": "PR"
        },
        {
            "countryName": "República Dominicana",
            "countryCode": "DO"
        },
        {
            "countryName": "Uruguay",
            "countryCode": "UY"
        },
        {
            "countryName": "Venezuela",
            "countryCode": "VE"
        }
    ];

    var countryCode;
    var countryName;
    var countryBox = "";
    var countryBoxTemplate = $("#CountryBox_Template").clone();

    for (var i in countryList) {

        countryName = countryList[i].countryName;
        countryCode = countryList[i].countryCode;
        
        countryBox += countryBoxTemplate.html();

        countryBox = countryBox.replace(/@@CountryName@@/gi, countryName);
        countryBox = countryBox.replace(/@@CountryCode@@/gi, countryCode);

    }
    return countryBox;
}


function SelectCountry(country) {
    $("#selectedCountry").attr("country", country);
    var img = $("table[country='" + country + "']").find("td").eq(0).html();
    var countryName = $("table[country='" + country + "']").find("td").eq(1).html();
    $("#selectedCountry").find("td").eq(0).html(img);
    $("#selectedCountry").find("td").eq(1).html(countryName);
    $("#selectedCountry").click();
    SelectedCountryCallback(country);
}


(function ($) {
    var cache = [];
    // Arguments are image paths relative to the current page.
    $.preLoadImages = function () {
        var args_len = arguments.length;
        for (var i = args_len; i--; ) {
            var cacheImage = document.createElement('img');
            cacheImage.src = arguments[i];
            cache.push(cacheImage);
        }
    }
})(jQuery)
