/*
	Index
	| document.ready
	| window.load
	| rels
	| nav
	| forms
	| ajax
	| physiologicalFootwear
	| accordionQuestions
	| openLayer
	| notSupMaxPropert
	| ieBrowser
 */

/* +document ready */
jQuery(document).ready(function(){

	//links type
	rels();

	//masks
	$('input:text').setMask();

	//menu navigation
	$('#link-institutional').removeClass('active');
	nav();

	//forms
	forms();

	//ajax
	ajax();

	//accordion
	accordionQuestions();

	//watermark plugin
	$('.watermark').watermark();

	//only numbers
	$('.number').onlyNumber();

	//physiological footwear functions
	physiologicalFootwear();

	//layer
	openLayer();

	//analytics links
	analyticsLinks();

    //tooltips
    tooltips();

	//blogs
	blogsScripts();

});
/*  end document ready  */


/* +window.load */
$(window).load(function(){
	if(notSupMaxPropert()) { //ie6
		DD_belatedPNG.fix('.png-bg');
		ieBrowser();
	}
});
/*  end window.load */


/* +document ready functions */
function rels() {
	$("a[rel*=external]").attr("target", "_blank");
}

function nav() {

	$('ul#menu ul.submenu').addClass('hide');

	bodyId = $('body').attr('id');
	bodyClass = $('body').attr('class');

	$('#nav').find('a#link-' + bodyId).addClass('active');
	$('#nav').find('a#link-' + bodyClass).addClass('active');

	if($('.has-submenu').is('.active')){
		$('.has-submenu').next('ul.submenu').slideDown(1000);
	}

	$('.has-submenu').one('click', function(){
		linkSub = $(this);

		if(linkSub.is('.active')){
			linkSub.removeClass('active');
			linkSub.next('ul.submenu').slideUp(function(){
				nav();
			});
		} else {
			linkSub.addClass('active');
			linkSub.next('ul.submenu').slideDown(function(){
				nav();
			});
		}

		return false;
	});
	
}

function forms() {
    $('#institutional-search-form').submit(function(){
       if (!$('#search_keyword').val() || $('#search_keyword').val() == "BUSCA") {
           alert("Digite a sua busca!");
           return false;
       }
       return true;
    });

    $('#registered, #user_alter_password').change(function(){
		$('.password').slideToggle();
    });

	$('.default-form li input, .default-form li textarea').focus(function(){
		$(this).parents('li').addClass('focus');
	}).blur(function(){
		$(this).parents('li').removeClass('focus');
	});

	$('#filter-maps input:text').focus(function(){
		$(this).parent().addClass('focus');
	}).blur(function(){
		$(this).parent().removeClass('focus');
	});

	$('#content .default-form .input-file').change(function(){
		inputValue = $(this).val();
		$(this).parents('.file').find('.input-text').val(inputValue);
	});

    $('#add-child').click(function() {
		var childForm = $('#sac-children ul:first').clone(),
			index = $('#sac-children ul').length;

		childForm.attr('id','filho-'+(index+1));
		childForm.find('input,select').each(function(id,elm){
			$(elm).val('').attr('id',function(){
				return this.id.replace('[0]','['+(index)+']');
			}).attr('name',function(){
				return this.id.replace('[0]','['+(index)+']');
			});
		});
		childForm.find('label').each(function(id,elm){
			$(elm).attr('for',function(){
				return this.id.replace('[0]','['+(index)+']');
			});
		});

		$('#sac-children ul:last').after(childForm);
		return false;
    });

    $('#franchise-form #franchise_interest').change(function(){
		if ($(this).val() == 'Outras') {
			$('#interest-extra-container').removeClass('hide');
		} else {
			$('#interest-extra-container').addClass('hide');
		}
    });
    
    $('#franchise-form #franchise_scholarity').change(function(){
		if ($(this).val() == 'Ensino Superior' || $(this).val() == 'Pós Graduação' || $(this).val() == 'MBA') {
			$('#course-container').removeClass('hide');
		} else {
			$('#course-container').addClass('hide');
		}
    });

	$('#franchise-form #franchise_civil_status').change(function(){
		if ($(this).val() == 'Casado') {
			$('.spouse-container').removeClass('hide');
		} else {
			$('.spouse-container').addClass('hide');
		}
    });

	$('#franchise-form #franchise_other_activity').change(function(){
		if ($(this).val() == 'S') {
			$('#activity-extra-container').removeClass('hide');
		} else {
			$('#activity-extra-container').addClass('hide');
		}
    });

}

function ajax() {

    $('#store-form select.state').change(function(){
		var selectState = $(this);
        if (selectState.val()) {
            selectState.parents('ul').find('select.city')[0].options.length = 1;
            selectState.parents('ul').find('select.city')[0].options[0].text = 'Carregando cidades...';
            $.post(rootUrl + 'whereToFind/loadCities', {state: selectState.val(), franchise: $('#store-franchise').val()}, function(data){
                selectState.parents('ul').find('select.city').html(data);
            });
        }
	});

	$('select.selectState').change(function(){
		var selectState = $(this);
        if (selectState.val()) {
            selectState.parents('ul').find('.loadByState')[0].options.length = 1;
            selectState.parents('ul').find('.loadByState')[0].options[0].text = 'Carregando cidades...';
            $.post(rootUrl + 'franchises/loadCities', {state_id : selectState.val()}, function(data){
                selectState.parents('ul').find('.loadByState').html(data);
            });
        }
	});

    $('#franchise-form select.franchiseSelectState').unbind('change').change(function(){
		var selectState = $(this);
        if (selectState.val()) {            
            var citySelect = selectState.parents('span').next('span').find('.loadByState');
            citySelect[0].options.length = 1;
            citySelect[0].options[0].text = 'Carregando cidades...';
            $.post(rootUrl + 'franchises/loadCities', {state_id : selectState.val()}, function(data){
                citySelect.html(data);
            });
        }
	});

    $('#sac_uf_loja').change(function(){
        if ($(this).val()) {
            var citySelect = $('#sac_cidade_loja')[0];
            citySelect.options.length = 1;
            citySelect.options[0].text = 'Carregando cidades...';
            $.post(rootUrl + 'sac/loadCities',{state:$(this).val()},function(response){
                citySelect.options[0].text = 'Selecione a cidade';
                for(i=0;i<response.length;i++) {
                    citySelect.options[i+1] = new Option(response[i],response[i]);
                }
            },'json');
        }
    });

    $('a[rel=forgot-password]').click(function(response){
       if ($('input[alt=cpf]').val()) {
           $('.loader').fadeIn();
           $.post(rootUrl+'sac/forgotPassword',{cpf:$('input[alt=cpf]').val()},function(response){
               $('.validates').empty();
               $('<div>').addClass('validates-'+response.type).html(response.message).css({display:'none'}).appendTo($('.validates')).slideDown();
               $('.loader').fadeOut();
           },'json');
       } else {
           $('.validates').empty();
           $('<div>').addClass('validates-error').html('Informe o CPF').css({display:'none'}).appendTo($('.validates')).slideDown();
       }
       return false;
    });

    $('#rate div.can-vote').click(boysClubPostLike);

    $('#photo-like').one('click',owlClubPhotoLike);
    $('#container .list a.like').one('click',owlClubGalleryPhotoLike);

    $('#blogcoruja #pagination-links a').live('click',function(){
        var page = $(this).attr('rel').replace('page-','')
        var options = {page: page};
        if ($('#category_id').length) {
            options.category = $('#category_id').val();
        }
        $.post(rootUrl+controller+'/loadPosts',options,function(response){
           $('.other-posts').html(response)
        });
        return false;
    });
}

function boysClubPostLike() {
    var obj = $(this);
    obj.animate({opacity:'0.4'});
    $('#rate div').unbind('click');
    var type = (obj.hasClass('yes')) ? 'yes' : 'no';
    $.post(rootUrl+'boysClub/like',{value:type,id:$('#post_id').val()},function(response){
       if (response.error != "") {
           alert(response.error);
       } else {
           obj.find('b').html(response.count);
           alert('Participação efetuada com sucesso');
       }
       obj.animate({opacity:'1'});
       $('#rate div').click(boysClubPostLike);
    },'json');
    return false;
}

function owlClubGalleryPhotoLike() {
    var obj = $(this),
        loader = obj.siblings('.like-loader'),
        trackId = obj.attr('href').replace('#',''),
        photoId = obj.parents('li').find('input.photo-id').val();

    loader.fadeIn();
    $.post(rootUrl+'owlClub/like',{id:photoId},function(response){
        if (response.error != "") {
            alert(response.error);
        } else {
            obj.html(response.count);
            alert('Participação efetuada com sucesso');
            tracker('/site/clube-coruja/meu-filho-e-o-maximo/gostar/'+trackId);
        }
        loader.fadeOut();
        obj.one('click',owlClubGalleryPhotoLike);
    },'json');
    return false;
}

function owlClubPhotoLike() {
    var trackId = $(this).attr('href').replace('#','');    
    $('.like-loader').fadeIn();
    $.post(rootUrl+'owlClub/like',{id:$('#photo_id').val()},function(response){
       if (response.error != "") {
            alert(response.error);
       } else {
            $('.cont-1').html(response.count);
            alert('Participação efetuada com sucesso');
            tracker('/site/clube-coruja/meu-filho-e-o-maximo/gostar/'+trackId);
       }
       $('.like-loader').fadeOut();
       $('#photo-like').one('click',owlClubPhotoLike);       
    },'json');
    return false;
}

function accordionQuestions() {

	$('.item-accordion').addClass('hide');

	if($('.item-accordion').length){
		hashQuestion = location.hash;
		if(hashQuestion != ''){
			$('.accordion').find(hashQuestion + ' .item-accordion').removeClass('hide');
			$('.accordion').find(hashQuestion + ' .title-accordion').addClass('active');
		}
	}

	$('.title-accordion').bind('click', function(){
		activeAccordion = $(this);
		if(activeAccordion.is('.active')){
			activeAccordion.removeClass('active');
			activeAccordion.next('.item-accordion').slideUp();
		} else {
			$('.title-accordion').removeClass('active').next('.item-accordion:visible').slideUp('fast');
			activeAccordion.addClass('active');
			activeAccordion.next('.item-accordion').slideDown();
		}

		return false;
	});

}

function physiologicalFootwear() {

	if($('#physiological-footwear').length) {
		var linkTimeLine;
		$('.nav-time-line a').click(function(){
			linkTimeLine = $(this);
			$('.nav-time-line li.active').removeClass('active');
			linkTimeLine.parents('li').addClass('active');

			linkClass = linkTimeLine.attr('href');
			divInfo = $(linkClass);
			
			var leftAnimate = divInfo.position().left;
			$('.items').animate({'left':'-'+leftAnimate+'px'}, 500);

			return false;
		});
	}

}

function openLayer() {

	$('.list-clipping .open-layer').click(function(){
		var linkOpenLayer = $(this);
		
		$('#layer #layer-box').hide();
		$('#layer').fadeIn(500, function(){
			$('#layer #layer-box').fadeIn(750);
			var clippingId = linkOpenLayer.attr('href');
			clippingId = clippingId.replace('#','');
			$.post(rootUrl + 'institutional/clippingImages', {id : clippingId}, function(data){
				$('#layer-box').append(data);
				$('.cont .image-description:first').show();
				$('.cont #image-clpping img:first').show();
				$('#layer-box .loader').fadeOut(200);

				//next image
				$('#layer .next.ativo').live('click', function(){
					var linkObj = $(this);

					currentImage = $('.cont #image-clpping img:visible');
					nextImage = currentImage.next('img');

					currentDescription = $('.cont p.image-description:visible');
					nextDescription = $('.cont p.image-description:visible').next('.image-description');

					if(nextImage.next('img').length == 0){
						$('#layer .next.ativo').removeClass('ativo');
					} else {
						$('#layer .next').addClass('ativo');
					}

					$('#layer .prev').addClass('ativo');

					animateImage(currentImage, nextImage, currentDescription, nextDescription);
					
					return false;
				});

				//previous image
				$('#layer .prev.ativo').live('click', function(){
					var linkObj = $(this);

					currentImage = $('.cont #image-clpping img:visible');
					prevImage = currentImage.prev('img');

					currentDescription = $('.cont p.image-description:visible');
					nextDescription = $('.cont p.image-description:visible').prev('.image-description');

					if(prevImage.prev('img').length == 0){
						$('#layer .prev.ativo').removeClass('ativo');
					} else {
						$('#layer .prev').addClass('ativo');
					}

					$('#layer .next').addClass('ativo');

					animateImage(currentImage, prevImage, currentDescription, nextDescription);

					return false;
				});
			});
		});

		return false;
	});
	
	$('#overlay, .close').click(function(){
		$('#layer').find('.cont').remove();
		$('#layer').fadeOut(700);
		return false;
	});

}

function animateImage(currentImage, nextImage, currentDescription, nextDescription){

	currentDescription.fadeOut(350, function(){
		nextDescription.fadeIn();
	});

	currentImage.fadeOut(350, function(){
		$('.cont .image').animate({queue : false, marginLeft : '-' + (nextImage.width()/2) + 'px'});
		$('#image-clpping').animate({width : nextImage.width(), height : nextImage.height(), queue : false}, function(){
			nextImage.fadeIn();
		});
	});

}

function analyticsLinks(){
	$('a[rel*=analytics_]').click(function(){
		link = $(this);
		track = link.attr('rel');
        track = track.substring(track.indexOf('analytics_'));
		track = track.replace('analytics_', '');
		tracker(track);
	});
}

function openLogin(){
	alert('Login');
}

function openRegister(){
	alert('Cadastro');
}

function tooltips() {
    if (typeof $.fn.qtip == "function") {
        $.fn.qtip.styles.girl = {
           tip: 'topMiddle',
           border: {
              width: 1,
              radius: 3,
              color: '#FA3889'
           },
           background: '#FFDBE7',
           color: '#FA3889',
           classes: { tooltip: 'qtip-girl', content: 'qtip-content-girl' }
        };

		$.fn.qtip.styles.boy = {
           tip: 'topMiddle',
           border: {
              width: 1,
              radius: 3,
              color: '#0A83D7'
           },
           background: '#D3E7F2',
           color: '#0A83D7',
           classes: { tooltip: 'qtip-boy', content: 'qtip-content-boy' }
        };

        $.fn.qtip.styles.owl = {
           tip: 'topMiddle',
           border: {
              width: 1,
              radius: 3,
              color: '#D2EEF1'
           },
           background: '#187C8C',
           color: '#FFF',
           classes: { tooltip: 'qtip-owl', content: 'qtip-content-owl' }
        };

        var options = {
            content: {
                    text: false
            },
            position: {
                corner: {
                    target: 'bottomMiddle',
                    tooltip: 'topMiddle'
                },
                adjust: {
                    x: 0
                }
            },
            style: {
                name: 'owl',
                padding: '7px 13px',
                width: {
                    max: 210,
                    min: 0
                },
                tip: true
            }
        };

        if ($('#top .send-picture').length) {
            options.style.name = 'owl';
            if ($.browser.msie && jQuery.browser.version.substr(0,1) == 7) {
                options.position.adjust.x = 300;
                options.position.adjust.y = 100;
            }
            $('#top a.send-picture[href][title]').qtip(options);
        }

        if ($('#btn-new-topic').length) {
            options.position.corner.tooltip = 'topLeft';
            options.position.adjust.x = -140;
            options.style.name = 'girl';
            $('#btn-new-topic[href][title]').qtip(options);
        }

		if ($('#blog-meninas #link-twitter').length) {
            options.position.corner.tooltip = 'topLeft';
            options.position.adjust.x = 0;
            options.style.name = 'girl';
            $('#link-twitter[href][title]').qtip(options);
        }

		if ($('#blog-meninos a#twitter').length) {
            options.position.corner.tooltip = 'topLeft';
            options.position.adjust.x = 0;
            options.style.name = 'boy';
            $('a#twitter[href][title]').qtip(options);
        }

		if ($('#blogcoruja a#twitter').length) {
            options.position.corner.tooltip = 'topLeft';
            options.position.adjust.x = 0;
            options.style.name = 'owl';
            $('a#twitter[href][title]').qtip(options);
        }

        if ($('#rate div.cannot-vote').length) {
            options.position.corner.tooltip = 'topLeft';
            options.position.adjust.x = 0;
            options.style.name = 'boy';
            $('#rate div.cannot-vote').qtip(options);
        }
    }
}

function cpfVerication(cpf) {
	if (cpf.charAt(3) == '.') {
		cpf = cpf.substr(0,3) + cpf.substr(4);
	}

	if (cpf.charAt(6) == '.') {
		cpf = cpf.substr(0,6) + cpf.substr(7);
	}

	if (cpf.charAt(9) == '-') {
		cpf = cpf.substr(0,9) + cpf.substr(10);
	}

	if (cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" ||
		cpf == "22222222222" ||	cpf == "33333333333" || cpf == "44444444444" ||
		cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" ||
		cpf == "88888888888" || cpf == "99999999999")
		return false;
	soma = 0;
	for (i=0; i < 9; i ++)
		soma += parseInt(cpf.charAt(i)) * (10 - i);
	resto = 11 - (soma % 11);
	if (resto == 10 || resto == 11)
		resto = 0;
	if (resto != parseInt(cpf.charAt(9)))
		return false;
	soma = 0;
	for (i = 0; i < 10; i ++)
		soma += parseInt(cpf.charAt(i)) * (11 - i);
	resto = 11 - (soma % 11);
	if (resto == 10 || resto == 11)
		resto = 0;
	if (resto != parseInt(cpf.charAt(10)))
		return false;
	return true;
}

function validateCpf() {
	var cpf = $('#franchise_cpf');
	var val = cpf.val();

	check = cpfVerication(val);

	if(!check){
		return [[cpf[0], "CPF inválido"]];
	}

	return true;
}

function validateSpouseCpf() {
	if($('.spouse-container').is(':visible')){
		var cpf = $('#franchise_spouse_cpf');
		var val = cpf.val();

		check = cpfVerication(val);

		if(!check){
			return [[cpf[0], "CPF do cônjuge inválido"]];
		}
	}
	return true;
}

function blogsScripts() {

	$('.cannot-post').click(function(){
		return false;
	});

}
/* end document ready functions */


/* +ie hacks */
function notSupMaxPropert() { // não suporta CSS max properties
	if (typeof document.body.style.maxHeight === "undefined") return true;
	else return false;
}

function ieBrowser(){

	if($('#home').length){
		htmlBrowser = '<div id="browser"><div class="browser-content"><a href="http://www.bibi.com.br" class="bibi-logo hide-text">Bibi</a><span class="text-browser">recomenda a atualização do seu navegador para acessar este site. <strong>Faça o download aqui:</strong></span><ul class="list"><li><a href="http://www.microsoft.com/windows/internet-explorer/" class="ie-link hide-text" rel="external" title="Internet Explorer">Internet Explorer</a></li><li><a href="http://www.google.com/chrome" class="chrome-link hide-text" rel="external" title="Google Chrome">Google Chrome</a></li><li><a href="http://www.mozilla.com/" class="firefox-link hide-text" rel="external" title="Mozilla Firefox">Mozilla Firefox</a></li></ul><a href="#" class="close hide-text">Fechar sugestão</a></div></div>';

		$('body').prepend(htmlBrowser);

		$('#browser').slideDown(1000);

		$('#browser .ie-link').click(function(){
			tracker('site/atualizar-navegador/internet-explorer');
		});
		$('#browser .chrome-link').click(function(){
			tracker('site/atualizar-navegador/google-chrome');
		});
		$('#browser .firefox-link').click(function(){
			tracker('site/atualizar-navegador/mozilla-firefox');
		});

		$('#browser .close').click(function(){
			$('#browser').slideUp(500);
			tracker('site/atualizar-navegador/fechar');
		});
	}
	
}
/* end ie hacks */

/* +other functions */
function resizeMenu(height) {
    $('#menu-blog').height(height);
}
/* end other functions */