﻿//IE6 users
if ($.browser.msie && $.browser.version=="6.0") {

	function createCookie(name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	}
	
	function readCookie(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}
	
	function eraseCookie(name) {
		createCookie(name,"",-1);
	}
	if(!readCookie('visitedPreviously')){
			var modalWindow = {
				parent:"body",
				content:null,
				width:null,
				height:null,
				open:function()
				{
					var modal = "<div id='modal-overlay'></div>";
					modal += "<div id='modal-window' style='width:" + this.width + "px; margin-left:-" + (this.width / 2) + "px;'>";
					modal += this.content;
					modal += "</div>";	
			
					$(this.parent).prepend(modal);
					this.height=0-($("#modal-window").height()/2);
					$("#modal-window").css({marginTop:this.height}).append("<a class='close-window'></a>");
				}
			};		
			
			modalWindow.width = 420;
			modalWindow.height = 405;
			modalWindow.content = "<div class='genericModal'><h2>Atenção!</h2><h3>O seu browser (Internet Explorer 6)<br/>não é suportado.</h3></div>";
			modalWindow.open();
			$(".close-window, #modal-overlay").live('click',function(){
				document.getElementById("modal-window").removeNode(true);
				document.getElementById("modal-overlay").removeNode(true);
			});

		createCookie('visitedPreviously', 'visitedPreviously', 5);   // 5 days persistence
	}

}
var $ie6HeaderNotice = $('#ie6notice');
if($ie6HeaderNotice.length)
{
	$ie6HeaderNotice.find('.close').click(function(e)
	{
		e.preventDefault();
		$ie6HeaderNotice.slideUp();
	});
}


//validate emails
function validateEmail(email){
	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
	return emailPattern.test(email);
}


//menu
var $mainMenu = $('#menu');
var $mainSubMenu = $mainMenu.find('ul');
var mainSubMenuHeight = $mainMenu.find('ul:first').outerHeight();
$mainMenu.children('li').hover(function()
{
	var $this = $(this);
    $this.children('a').addClass('active');
	if ($this.children('ul').length>0){
		$this.children('ul').stop().show().animate({
			'opacity': '1',
			'height': mainSubMenuHeight
		});
	}
}, function() {
    var $this = $(this);
    $this.children('a').removeClass('active');
	if ($this.children('ul').length>0){
		$this.children('ul').stop().animate({
			'opacity': '0',
			'height': 0
		}, function() {
			$this.children('ul').hide();
		});
	}
    Cufon.refresh();
});
$mainSubMenu.css({ 'height': 0 }).hide();


//set convert classes
Cufon.replace('.convertFont', {});
Cufon.replace('.convertFontLink', {hover: true});


//(function($) {

	if ($('.vcard .email').length > 0)
	{
		var fineEmail = $('.vcard .email').attr('rel').replace("/", "@");
		$('.vcard .email').attr('href', 'mailto:' + fineEmail).html(fineEmail);
	}


    window.GlobalFn = {
        //get urls
        URL: {
            login: null,
            basePath: null,

            init: function(callback) {

                /* If the callback is a function, add it to the queue for synchronous execution */
                if ($.type(callback) === 'function') {
                    GlobalFn.URL.queue.push(callback);
                }

                if (GlobalFn.URL.status == 2) {
                    /* Data is already fetched, run the waiting callback immediatly */
                    GlobalFn.URL.ready();
                }

                /* Only run ajax if it's not ran before */
                if (GlobalFn.URL.status === 0) {
                    GlobalFn.URL.status = 1;

                    $.ajax({
                        url: urlsJson,
                        dataType: 'json',
                        success: function(data) {
                            if (data !== null && data.urls.length > 0) {
                                for (var prop in data.urls[0]) {
                                    GlobalFn.URL[prop] = data.urls[0][prop];
                                }
                            }

                            /* It's fetched, set a dirty flag and run the callbacks */
                            GlobalFn.URL.status = 2;
                            GlobalFn.URL.ready();
                        },
                        error: function() {
                        }
                    });
                }
            },
            status: 0, /* status, 0 is no ajax, 1 is ajax, 2 is finished */
            queue: [], /* callback queue */
            ready: function() {
                /* loop through the waiting functions, sycnhronous */
                for (var i = 0, l = GlobalFn.URL.queue.length; i < l; i++) {
                    GlobalFn.URL.queue[i]();
                }
                /* empty the queue */
                for (var ii = 0; ii < GlobalFn.URL.queue.length; ii++) {
                    GlobalFn.URL.queue.splice(ii, 1);
                    ii--;
                }
            }
        },
        //modal window
        /*modalWindow: function(href, class, complete) {
            if ($.type(href) == 'string') {
                href = $('<a />', { 'href': href });
            }*/
		modalWindow: function(href, extra) {
            if ($.type(href) == 'string') {
				if($.type(window._gaq) != "undefined"){
					_gaq.push(['_trackPageview', href]);
				}
                href = $('<a />', { 'href': href });
            }
			if($.type(extra) == "undefined") {extra={};}
            extra.open= true;
			extra.onLoad = function() {
				if($('#bestContentHighlights').length){
					// hack to prevent slideshow from EXPLODING!!
					var bstcnt = $('#bestContentSelection a.active').attr('href').substr(1);
					$.fn.loadBestContent(bstcnt);
				}
				if ($.type(extra.cssClass) == 'string') {
					$('#cboxOverlay, #colorbox').attr('class', extra.cssClass);
				} else {
					$('#cboxOverlay, #colorbox').removeAttr('class');
				}
				$('#cboxClose').hide();
				if ($.type(extra.onload) == 'function') {
					extra.onload.apply(this);
				}
            };
			extra.onClosed = function() {
				if ($.type(extra.onclosed) == 'function') {
					extra.onclosed.apply(this);
				}
            };
			extra.onComplete = function() {
				$('#cboxClose').show();
				if ($.type(extra.oncomplete) == 'function') {
					extra.oncomplete.apply(this);
				}
            };
			href.colorbox(extra);
        },
        genericModal: function(text, extra) {
			if($.type(extra) == "undefined") {extra={};}
            extra.html= '<div class="genericModal">' + text + '</div>';
			extra.onLoad = function() {
				if ($.type(extra.cssClass) == 'string') {
					$('#cboxOverlay, #colorbox').attr('class', extra.cssClass);
				} else {
					$('#cboxOverlay, #colorbox').removeAttr('class');
				}
				$('#cboxClose').hide();
				if ($.type(extra.onload) == 'function') {
					extra.onload.apply(this);
				}
            };
			extra.onComplete = function() {
				$('#cboxClose').show();
				if ($.type(extra.oncomplete) == 'function') {
					extra.oncomplete.apply(this);
				}
            };
           $.colorbox(extra);
        },
        genericErrorModal: function() {
            window.GlobalFn.genericModal('<h2 class="errorModal">Ocorreu um falha técnica</h2><h3>volta a tentar mais tarde</h3>');
        },
        //deal with services
        serviceLogged: function(data) {
            var result = {
                logged: true,
                success: true
            };

            if (!data.status.success) {
                for (var it = 0; it < data.status.errors.length; it++) {
                    if (data.status.errors[it].code === 'Auth') {
                        result.logged = false;
                    }
                }
            }
            result.success = data.status.success;

            return result;
        }
    };

    GlobalFn.URL.init();


    $(function() {
        //search
        var search = $('#search'),
      		searchInput = search.find('.string'),
        	searchSubmit = search.find('.submitBtn');
        if (!$('#header').hasClass('homepage')) {
            var searchTip = $('#search').find('.tip'),
           		advancedFields = $('#advancedFields'),
            	headerHeight = $('#header').height(),
           		advancedSearchGrowHeight = advancedFields.height() - searchTip.height();
            search.delegate('#advancedSearch', 'click keypress', function(e, first) {
                e.preventDefault();
                var advancedSearchLabel = $(this);
                if (advancedSearchLabel.hasClass('opened') && first !== true) {
                    searchTip.slideDown(300);
                    $('#header, #headerContainer, #headerContentColumn').animate({
                        'height': headerHeight
                    }, function() {
                        advancedSearchLabel.text('Pesquisa Avançada').removeClass('opened');
                        searchInput.select();
                    });
                } else {
                    searchTip.slideUp(600);
                    $('#header, #headerContainer, #headerContentColumn').animate({
                        'height': headerHeight + advancedSearchGrowHeight
                    }, function() {
                        advancedSearchLabel.text('Pesquisa Simples').addClass('opened');
                        searchInput.select();
                    });
                }
            });
            if ($('#advancedSearch').hasClass('opened')) {
                $('#advancedSearch').trigger('click', [true]);
            }
        }
        //trim selected option
        if (search.length)
        {
            search.find('#advancedFields').find('select').each(function() {
                //if value already defined then trim it
                if ($(this).find('option[selected="selected"].sub')) {
                    //trim the selected option
                    var $option = $(this).find('option[selected="selected"].sub');
                    var $optionTrimmed = $.trim($option.text());
                    $option.addClass('selected').text($optionTrimmed);
                }

                //on change select value
                $(this).change(function() {
                    var $this = $(this);

                    //put the previous selected option with the expected spaces
                    var $previousOption = $this.find('option.selected');
                    var spaces = "\u00a0\u00a0\u00a0\u00a0";
                    $previousOption.text(spaces + $previousOption.text()).removeClass('selected');

                    //only do this to subcategories
                    if ($this.find('option:selected').is('.sub')) {
                        //trim the selected option
                        var $option = $this.find('option:selected');
                        var $optionTrimmed = $.trim($option.text());
                        $option.addClass('selected').text($optionTrimmed);
                    }
                });
            });
        }

        searchSubmit.bind('click keypress', function(e)
        {
            var $this = $(this);
            $this.blur();
            //avoid submitting the value on IE
            if (searchInput.attr('placeholder') == searchInput.val())
            {
            	searchInput.val('');
            }
            //check if any value was submitted
            var $values = $this.parents('#search').find(':input').not('[type="hidden"]').serializeArray ();
			var $filled = $.map($values, function(e)
							{
								if (e.value !== '')
								{
									return e.name;
								}
							});
            if ($filled == 0) {
                e.preventDefault();
                searchInput.focus();
            }
            else
            {
                //add progress button so user knows something is being processed
                $this.css({ 'background': 'none' }).find('.progressBtn').css({ 'display': 'block' });
            }
        });
        //if search form is submit by clicking enter(keyCode = 13) on the input then do the same above
        searchInput.keypress(function(e)
        {
            if (e.keyCode == 13)
            {
                searchSubmit.click();
            }
        });
    });

    //testimonies
    $.fn.showTestimonies = function(url) {
        var testimonyContainer = $('#testimony');
        $.ajax({
            url: url,
            dataType: 'json',
            success: function(data) {
                var html = '';
                for (i = 0; i < data.testimonies.length; i++) {
                    if (data.testimonies[i].image !== undefined) html += '<article class="content" style="background:transparent url(' + data.testimonies[i].image + ') right top no-repeat;">';
                    if (data.testimonies[i].story1 !== undefined) html += '<p class="story1">' + data.testimonies[i].story1 + '</p>';
                    if (data.testimonies[i].story2 !== undefined) html += '<p class="story2">' + data.testimonies[i].story2 + '</p>';
                    if (data.testimonies[i].name !== undefined) html += '<p class="name">' + data.testimonies[i].name + '</p>';
                    if (data.testimonies[i].jobAge !== undefined) html += '<p class="jobAge">' + data.testimonies[i].jobAge + '</p>';
                    if (data.testimonies[i].image !== undefined) html += '</article>';
                }
                testimonyContainer.html(html);
                var testimonyList = testimonyContainer.find('article');
                testimonyList.first().addClass('active');
                testimonyList.not('.active').hide();
                (function testimonySlideShow() {
                    setTimeout(function() {
                        var $current = testimonyList.filter('.active');
                        var $next = testimonyList.eq($current.index() + 1);
                        if (!$next.length) $next = testimonyList.eq(0);
                        $current.removeClass('active').fadeOut(500, function() {
                            $next.addClass('active').fadeIn(500);
                        });
                    }, 7000);
                })();
            }
        });
    };




        //init modal window
        $('body').delegate('[rel=modal]', 'click keypress', function(e) {
            e.preventDefault();
            $this = $(this);
            window.GlobalFn.modalWindow($this.attr('href'));
        });

        

        /*
        //inputs type support
        if(!Modernizr.inputtypes.search){
        $('input[type="search"]').each(function(){
        var $this = $(this);
        marker = $('<span />').insertBefore($this);
        $this.detach().attr('type', 'text').insertAfter(marker);
        marker.remove();
        });
        }
        */

        //inputs placeholders support
        if (!Modernizr.input.placeholder) {

            $('input[name="password"]').hide().after('<input type="text" name="fakePassword" placeholder="password" />');

            $('input[placeholder]').each(function() {
                var $this = $(this);
                if ($.trim($this.val()) === '' && $this.attr('placeholder') != '') {
                    $this.val($this.attr('placeholder')).addClass('empty');
                    $this.focus(function() {
                        if ($this.attr('name') == "fakePassword") {
                            $this.hide();
                            $('input[name="password"]').show().focus();
                        } else if ($this.val() == $this.attr('placeholder')) {
                            $this.val('').removeClass('empty');
                        }
                    });
                    $this.blur(function() {
                        if ($.trim($this.val()) == '') {
                            $this.val($this.attr('placeholder')).addClass('empty');
                            if ($this.attr('name') == "password") {
                                $this.hide();
                                $('input[name="fakePassword"]').addClass('empty').show();
                            }
                        }
                    });
                }
            });

        }


        
            //open login dialog
            $("a.login").die("click");
            $('a.login').live('click', function(e) {
                e.preventDefault();
                window.GlobalFn.modalWindow($(this).attr('href'));
            });
            
            //login form
            $('body').delegate('.loginForm', 'submit', function(e) {
                e.preventDefault();
                var $this = $(this);
				GlobalFn.URL.init(function() {
					var postData = $this.serialize();
					$.post(GlobalFn.URL.loginService,
						postData,
						function(data) {
							var errorMessage;
							if (data.status.success == false) {
								if (data.status.errors[0].desc == 'Missing email' && data.status.errors[0].desc == 'Missing password') {
									errorMessage = 'preencha email e password';
								} else if (data.status.errors[0].desc == 'Missing email') {
									errorMessage = 'preencha email';
								} else if (data.status.errors[0].desc == 'Missing password') {
									errorMessage = 'preencha password';
								} else if (data.status.errors[0].desc == 'wrong credentials') {
									errorMessage = 'email ou password incorrectos';
								}
								$this.find('p').remove();
								$this.prepend('<p class="errorContainer">' + errorMessage + '</p>');
							} else {
								window.location = window.location; //refreshes the page
							}
						},
						"json");
				});
            });
            
            //recover form
            $('body').delegate('.recoverForm', 'submit', function(e) {
                e.preventDefault();
                var $this = $(this);
				GlobalFn.URL.init(function() {
					var postData = $this.serialize();
					$.post(GlobalFn.URL.ServiceRecoverPassword,
						postData,
						function(data) {
							var errorMessage;
							if (data.status.success == false) {
								var errorMessage = "erro";
								if (data.status.errors[0].desc == 'Missing email') {
									errorMessage = 'preencha email';
								} else if (data.status.errors[0].desc == 'Email incorrecto') {
									errorMessage = 'email incorrecto';
								} else if (data.status.errors[0].desc == 'wrong credentials') {
									errorMessage = 'deves confirmar o teu registo';
								}
								$this.find('p.errorContainer').remove();
								$this.find('p').after('<p class="errorContainer">' + errorMessage + '</p>');
							} else {
							  $this.find('p.errorContainer').remove();
							  $this.find('input').remove();
								$this.find('p').after('<p class="successContainer">verifica o teu e-mail</p>');
							}
						},
						"json");
				});
            });

            $(function() {
                //votes
                var $rating = $('#rating .vote');
                var $recipeId = $('#rating .vote').attr('rel');
                if ($rating.length > 0) {
                    GlobalFn.URL.init(function() {
                        $.ajax({
                            url: window.GlobalFn.URL.basePath + '/assets/scripts/jquery.rating.pack.js',
                            dataType: 'script',
                            complete: function() {
                                $rating.find('span[disabled=disabled]').find('.star-rating').live('click', function() { window.GlobalFn.modalWindow(window.GlobalFn.URL.loginNeeded); })
                                $rating.find('input').rating({
                                    callback: function(value, link) {
                                        $.post(GlobalFn.URL.ServiceRecipeVote + "/" + $recipeId,
								    { "Rating": value },
								    function(data) {
								        if (data.status.success) {
								            $rating.find('label').html('Obrigado pelo seu voto!').addClass('applied');
								        }
								        else {
								            $rating.find('label').html('Falha Técnica! Por favor tente mais tarde.').addClass('applied');
								        }
								    },
								    "json");
                                    }
                                });
                            }
                        });
                    });
                }
                //short url
                if ($('#copyClipboard').length > 0) {
                    GlobalFn.URL.init(function() {
                        $.getScript(window.GlobalFn.URL.basePath + '/assets/scripts/ZeroClipboard.js', function() {
                            ZeroClipboard.setMoviePath(window.GlobalFn.URL.basePath + '/assets/flash/ZeroClipboard10.swf');
                            var clip = new ZeroClipboard.Client();
                            $('#shortURL').focus(function() {
                                $(this).select();
                            });
                            clip.glue('copyClipboard', 'clipboardContainer');
                            clip.setText($('#shortURL').val());
                            clip.setHandCursor(true);
                        });
                    });
                }

            });
			




        //social share
        var socialShare = $('#socialShare');
        if (socialShare.length > 0) {
            socialShare.find('.sendTo, .blogIt').hide();

            var sendTo = socialShare.find('.sendTo');
            var blogIt = socialShare.find('.blogIt');

            //send to
            socialShare.delegate('.mail a', 'click keypress', function(e) {
                e.preventDefault();
                var $this = $(this);
                if (!$this.hasClass('active')) {
                    $this.addClass('active');
                    sendTo.css({
                        'opacity': '0'
                    }).slideDown(function() {
                        $(this).animate({
                            'opacity': '1'
                        });
                    });
                } else {
                    sendTo.animate({
                        'opacity': '0'
                    }, function() {
                        $(this).slideUp();
                        $this.removeClass('active');
                    });
                }
            });
            window.sendByMailReturn = function(data, $this) {
                // aqui tem de se fazer o final da coisa
                // comunicar ao utilizador se a acção foi bem sucedida ou não
                if (data.status.success === true) {
                    socialShare.find('.mail a').removeClass('active');
                    sendTo.animate({
                        'opacity': '0'
                    }, function() {
                        $(this).slideUp(function(){
                        	//clear values on "To:"
                        	$(this).find('.to').find('input').val('');
                        });
                        $this.removeClass('active');
                    });
                }
                else {
                    window.GlobalFn.genericErrorModal();
                }
            };

            //blog it
            socialShare.delegate('.blog a', 'click keypress', function(e) {
                e.preventDefault();
                var $this = $(this);
                if (!$this.hasClass('active')) {
                    $this.addClass('active');
                    blogIt.css({
                        'opacity': '0'
                    }).slideDown(function() {
                        $(this).animate({
                            'opacity': '1'
                        });
                    });
                } else {
                    blogIt.animate({
                        'opacity': '0'
                    }, function() {
                        $(this).slideUp();
                        $this.removeClass('active');
                    });
                }
            });
            $('.fb_share_no_count').css({ 'display': 'block' }).find('.fb_share_count_inner').html('0');

        }


        //accept only numbers on input
        if ($(".numbersOnly").length > 0) {
            $(".numbersOnly").keypress(function(e) {
                if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                    //error msg
                    return false;
                }
            });
        }
			


    /*
    * Auto-growing textareas; technique ripped from Facebook
    */
    $.fn.autogrow = function(options) {

        this.filter('textarea').each(function() {

            var $this = $(this),
                minHeight = $this.height(),
                lineHeight = $this.css('lineHeight');

            var shadow = $('<div></div>').css({
                position: 'absolute',
                top: -10000,
                left: -10000,
                width: $(this).width() - parseInt($this.css('paddingLeft')) - parseInt($this.css('paddingRight')),
                fontSize: $this.css('fontSize'),
                fontFamily: $this.css('fontFamily'),
                lineHeight: $this.css('lineHeight'),
                resize: 'none'
            }).appendTo(document.body);

            var update = function() {

                var times = function(string, number) {
                    for (var i = 0, r = ''; i < number; i++) r += string;
                    return r;
                };

                var val = this.value.replace(/</g, '&lt;')
                                    .replace(/>/g, '&gt;')
                                    .replace(/&/g, '&amp;')
                                    .replace(/\n$/, '<br/>&nbsp;')
                                    .replace(/\n/g, '<br/>')
                                    .replace(/ {2,}/g, function(space) { return times('&nbsp;', space.length - 1) + ' '; });

                shadow.html(val);
                $(this).css('height', Math.max(shadow.height() + parseFloat(lineHeight), minHeight));

            };

            $(this).change(update).keyup(update).keydown(update);

            update.apply(this);

        });

        return this;

    };
	if ($(".autogrow").length > 0) {
    	$('.autogrow').autogrow();
	}




//})(jQuery);
