var DEBUG_MODE = false;
var FECHA_AUTOMATICA = false;
var FECHA_locked = [];

function log(obj) {
    if (DEBUG_MODE)
        console.log(obj);
}

	function split( val ) {
		return val.split( /,\s*/ );
	}
	function extractLast( term ) {
		return split( term ).pop();
	}

function set_search(obj) {
    var $type = $(obj).attr("s_type");
    $(obj).bind( "keydown", function( event ) {
			if ( event.keyCode === $.ui.keyCode.TAB &&
					$( this ).data( "autocomplete" ).menu.active ) {
				event.preventDefault();
			}
		})
        .autocomplete({
		  source: function(request, response) {
		    var $this = $(this.element).prev(".loading");
			$.ajax({ 
			    url: SITE_URL+"ajax/pais_estado_cidade", dataType:'json', type:"post",
                data: {term: extractLast( request.term ), type: $type },            
                success: function (resp) {
                    $this.fadeOut('fast', function () { $(this).remove() });
                    delete $this;
                    
                    
                    var labels = [];
                    
                    $.each(resp, function (i, val) {
                        var $tmp = val.label.split("|");
                        labels.push({
                            bandeira : $tmp.length > 1 ? $tmp[0] : '',
                            label : $tmp.length > 1 ? $tmp[1] : $tmp[0] 
                        });
                        resp[i].label = $tmp.length > 1 ? $tmp[1] : $tmp[0];
                    });
                    
                    response(resp);

                    $(".ui-autocomplete a:visible").each(function (i, val) {
                        
                       if (labels.length > i && labels[i].bandeira != '') {
                          $(this).html('<img src="'+labels[i].bandeira+'" width="16" height="11" alt=""  /> '+labels[i].label);
                       }
                       
                    });
                }
            });
		},
		search: function() {
			// custom minLength

            
			var term = extractLast( this.value );
			if ( term.length < 3 ) {
				return false;
			}
            
            if ($(this).prev('.loading').length == 0 ) {
                $(this).before('<div class="loading" style="margin-left:'+($(this).outerWidth() - 20)+'px; margin-top: '+Math.ceil( ($(this).outerHeight() - 16) / 2  )+'px"></div>');
            }
		},
        focus: function() {
			// prevent value inserted on focus
			return false;
		},

        select: function( event, ui ) {
            if ($(this).hasClass('search-destino')) {
               this.value = ui.item.value;   
            } else {
    			var terms = split( this.value );
    			// remove the current input
    			terms.pop();
    			// add the selected item
    			terms.push( ui.item.value );
    			// add placeholder to get the comma-and-space at the end
    			terms.push( "" );
    			this.value = terms.join( ", " );
    			return false;
            }
		},

		open: function() {
            
			$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
		},
		close: function() {
            $(this).prev('.loading').remove();
			$(this).removeClass("ui-corner-top").addClass("ui-corner-all");

		}
	});    
    
}

$(function(){
    $(".arrow-lines-30 li, .arrow-lines-25 li, .arrow-lines-40 li").hover(function () {
       $(this).addClass('arrow-hover'); 
    }, function (ev) {
        $(this).removeClass('arrow-hover');
    });
    
    $('.has_mouseover').live('mouseover', function () {
        if (!$(this).hasClass('active')) {
            var src = $(this).attr('src').split('.');
            var ext = src.pop();
            
            var tmp =  src.join('.').split('-');
            
            
            var last = tmp.pop();
            if (last != 'on')
                tmp.push(last);
            
            
            $(this).attr('src',tmp.join("-")+'-on.'+ext);
        }       
    }).live('mouseout', function () {
        if (!$(this).hasClass('active')) {

            var src = $(this).attr('src').split('.');        
            var ext = src.pop();
            
            var tmp = src.join('.').split('-');
            var last = tmp.pop();
            if (last != 'on')
                tmp.push(last);
    
            $(this).attr('src', tmp.join('-')+'.'+ext);
        }
    });
    
   //$(document).pngFix(); 
   $("#main-menu-list > li").hover(function () {
		$(this).addClass('hover');									   
	}, function () {
		$(this).removeClass('hover');
	});
   
    //$("#main-menu-list img").pngFix();
    
    $(".focus_clean").live('focus',function () {
        if ($(this).val() == $(this).attr('defaultValue'))
            $(this).val(''); 
    }).live('blur',function () {
        if ($(this).val() == '')
            $(this).val($(this).attr('defaultValue'));
    });
    


    $("#busca_texto").each(function () {
        set_search(this);
    });
    
    //$('.drop').weeMenu();
    $(".popup-geral").live('click',function (e) {
        e.preventDefault();
        
        $.fancybox(
            {
    		'transitionIn'	: 'elastic',
    		'transitionOut'	: 'elastic',
            'padding'       : 0,
    		'speedIn'		: 600, 
    		'speedOut'		: 200,
            'type'          : $(this).attr('fc_iframe') == 'true' ? 'iframe' : 'ajax',
            'autoDimensions' : $(this).attr('fc_auto') == 'true' ? true : false,
            'scrolling'     : false,
            'href'           : $(this).attr('href'),
            'showCloseButton' : false,
            'width'         : parseInt($(this).attr("fc_width")) > 0 ? parseInt($(this).attr("fc_width")) : '',
            'height'        : parseInt($(this).attr("fc_height")) > 0 ? parseInt($(this).attr("fc_height")) : ''
    	}); 

    }); 

    $(".imagem-pop-up").live('click',function (e) {
        e.preventDefault();
        
        $.fancybox(
            {
    		'transitionIn'	: 'elastic',
    		'transitionOut'	: 'elastic',
            'padding'       : 0,
    		'speedIn'		: 600, 
    		'speedOut'		: 200,
       
            'autoDimensions' : true,
            'scrolling'     : false,
            'href'           : $(this).attr('href'),
            'showCloseButton' : true
           
    	}); 

    }); 

    $(".pop-help").hover(function () {
        var $box = $(this).next('.help_popup_box');
        var box_width = 0;
        if ($box.length == 0) {     
            var width = 250;
            if (parseInt($(this).attr('pop_width')) > 0) {
                width = parseInt($(this).attr('pop_width'));
            }
            
            var tpl = new Template();
            tpl.use( $(this).attr('template') );
            
            $box = $("<div />").addClass('help_popup_box').width(width)
                        .html(tpl.render());
            $box.css({'position' : 'absolute'}).hide();

            box_width = width + 30; 
            $(this).after($box);
        } else {
            box_width = $box.outerWidth();
            
            if ($(this).attr('reload_template') == 'true') {
                var tpl = new Template();
                tpl.use( $(this).attr('template') );
                $box.html(tpl.render());
            }
        }
        var offset = null;
        if ($(this).attr('fix_in') == 'parent') {
            offset = $(this).parent().offset();
        } else {
            offset =$(this).offset();
        }
        
        
        
        
        
        $box.css({left: offset.left + $(this).outerWidth() - box_width, top : offset.top + $(this).outerHeight() });
        
        $box.show();         
    }, function () {
        $(this).next('.help_popup_box').hide();
    });


    $(".fancybox").each(function () {
       $(this).fancybox(
            {
    		'transitionIn'	: 'elastic',
    		'transitionOut'	: 'elastic',
            'padding'       : 0,
    		'speedIn'		: 600,
    		'speedOut'		: 200
    	});
    });
    
    var tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate()+1);
    
    var tomorrow_str = tomorrow.toBr("-");
    
    
    $(".calendario_open").each(function () {
        $(this).addClass('tem_calendario');
        $(this).focus(function () {
                var from = tomorrow_str;
                if ($(this).data("from"))
                    from = $(this).data("from");
                    
                $(this).weeCalendarOpen({from: from, input: $(this), blur_mode: true });
        }).mask("99-99-9999");
    });

    /*
     $(".calendario_open").live('focus',function () {
        //$(this).focus(function () {
            var from = tomorrow_str;
            if ($(this).data("from"))
                from = $(this).data("from");
                
            $(this).weeCalendarOpen({from: from, input: $(this), blur_mode: true });
       // })
    }).mask("99-99-9999");
    */
    
   
    
    /*$("#main-menu").each(function () {
        mlddminit(375);
    });*/
    
   /*$('.telefone_atendimento').cycle({
   		    fx:      'scrollDown', 
            speed:    10, 
            timeout:  5000,
            width  :  400  
   });*/
   
    $(" #main-menu-list ul ").css({display: "none"}); // Opera Fix
    $(" #main-menu li").hover(function(){
        var css = {visibility: "visible",display: "none"};
        if ($(this).parents('ul').length > 1) {
            css.marginLeft = $(this).width();
            css.marginTop = $(this).height() * -1; 
        }
    	$(this).find('ul:first').css(css).show();
    },function(){
    	$(this).find('ul:first').css({visibility: "hidden"});
    });
    
});

function newsletter(email_field, obj) {
    $("#"+email_field).attr('disabled', true).html('Cadastrando...');
    
    $.ajax({
        url : SITE_URL+'home/newsletter',
        data:'email='+$("#"+email_field).val(),
        type:'POST',
        success: function (response) {
            jAlert(response);
            $("#"+email_field).attr('disabled', false).html('E-mail');
        }
    });
}

/**
 * Template Class
 */
function Template(id) {
    this.html = "";
    this.values = [];
    this.ifs = [];
}
Template.prototype.clear = function () {
    this.values = [];
    this.ifs = [];
    return this;    
}
Template.prototype.use = function (id) {
    this.html = $("#template-"+id).html()+"";
    return this;    
}
Template.prototype.add = function (key, val) {
    this.values.push({"key":key, "val" : val });
    return this;    
}
Template.prototype.if_block = function (key, condition) {
    this.ifs.push({key: key, condition:condition});
    return this;
}

Template.prototype.add_some = function (values) {
    var $this = this;
    $.each(values, function (key, val) {
        $this.values.push({"key":key, "val" : val });    
    });
    
    return this;    
}
Template.prototype.render = function () {
    var html = this.html;
    var re;
    
    $.each(this.ifs, function (i, row) {
       if (row.condition == true) {
            re = new RegExp('#if '+row.key+"#","g");
    
            html = html.replace(re, '');
              
            re = new RegExp('#end '+row.key+"#","g");
    
            html = html.replace(re, '');  
       } else {
            // remove
            re = new RegExp('#if '+row.key+'#.*#end '+row.key+'#', 'g');
    
            html = html.replace(re, '');  
       } 
    });
    
    html = html.replace(/}/g, '>'); 
    html = html.replace(/{/g, '<');     
    $.each(this.values, function (i, option) {
        re = new RegExp('#'+option.key+";","g");

        html = html.replace(re, option.val);  
    });
    
    
    return html; 
}

Number.prototype.toMoney = function (decimal, decimal_del, thousand_del) {
    var value = 0;
    try {
        value =this.toFixed(decimal);
    } catch(e) {
        return this;
    }
    var tmp = value.toString().split(".");

    
    var result = [];
    var first  = false;
    var mod    = tmp[0].length % 3;

    
    for(var i=0; i<tmp[0].length; i++) {
        if (!first && i > 0 && i % (3 - 3 - mod) == 0) {
            result.push(thousand_del);
            first = true;
        } else if (first && i - mod % 3 == 0) {
            result.push(thousand_del);
        }
        result.push(tmp[0].charAt(i));
    }    
    
    return [result.join(""), tmp[1]].join(decimal_del);
}

Number.prototype.toMoneyBr = function () {
    try {
    return this.toMoney(2,',','.');
    } catch (e) {
        return '0,00';
    }
}


String.prototype.toMoney = function (decimal, decimal_del, thousand_del) {
    var tmp = new Number(this);
    return tmp.toMoney(decimal, decimal_del, thousand_del);
}
String.prototype.toMoneyBr = function () {
 
    return this.toMoney(2,',','.');
}

String.prototype.toNumber = function () {
    return parseFloat(this.replace('.','').replace('.', '').replace(',','.'));
}

String.prototype.isZeroValue = function () {
    
    var tmp = new Number(this);
    if (tmp == 0)
        return true;
    return false;
}

Number.prototype.isZeroValue = function () {
    if (this == 0)
        return true;
    
    return false;
}

String.prototype.toDate = function (delimiter) {
    var tmp = this.split(delimiter);


    if (tmp.length != 3) {

        return this;
    }

    var $ret = new Date(parseInt(tmp[2]),parseInt(tmp[1].ltrim("0"))-1, parseInt(tmp[0].ltrim("0")),15);
    

    return $ret;
}

Number.prototype.unsigned_zeros = function (zeros) {
    return this.toString().unsigned_zeros(zeros);   
}


String.prototype.ltrim = function (key) {
    if (this.substring(0,1) == key) {
        return this.substring(1, this.length);
    }
    return this;
}

String.prototype.unsigned_zeros = function (zeros) {
    var len = this.length;
    var zeros_vec = [];
	if (len < zeros) {
        var ate = zeros - len;
        for(var i=0; i<ate; i++)
            zeros_vec.push('0');    
        delete ate, len;        
    }
	return zeros_vec.join('') + this;
}

Date.prototype.toBrShort = function (delimiter) {
    return [(this.getDate() < 10 ? '0'+this.getDate() : this.getDate()), 
            (this.getMonth() + 1 < 10 ? '0'+(this.getMonth() +1 ) : this.getMonth() + 1 )].join(delimiter);
}
Date.prototype.toBr = function (delimiter) {
    return [(this.getDate() < 10 ? '0'+this.getDate() : this.getDate()), 
            (this.getMonth() + 1 < 10 ? '0'+(this.getMonth() +1 ) : this.getMonth() + 1 ),
            this.getFullYear()].join(delimiter);
}

Date.prototype.addDate = function (days) {
    this.setDate(this.getDate() + days);
    return this;
}

Date.prototype.daysDiff = function (date) {
    var time1 = Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()) / 1000 + 54000;
    var time2 = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) / 1000 + 54000;
    
    return Math.floor((time1 - time2) / 86400);
}


/**
  * End template Class
  */
  
function str_to_img(txt) {    
    var html = '';
    for (var i=0; i<txt.length; i++) {
        if (txt.charAt(i) == ' ')
            html += '<span class="space"></span>';
        else if (txt.charAt(i) == '-')
            html += '<span title="-" class="numbers n_" ></span>';  
        else if (txt.charAt(i) == '/')
            html += '<span title="/" class="numbers n_" ></span>';   
        else
            html += '<span title="'+txt.charAt(i)+'" class="numbers n'+txt.charAt(i)+'" ></span>'; 
    }

    return html;
}

String.prototype.replace_all = function (token, newtoken) {
    var tmp = this;
    while(tmp.indexOf(token) != -1) {
        tmp = tmp.replace(token, newtoken);    
    }
    return tmp;
}

String.prototype.toInt = function () {
    return parseInt(new Number(this) + 0);
}
