/*

Projeto: MRV Sustentavel - MRV Engenharia
Projeto URL: http://www.mrv.com.br

Autor: Gabriel Tadeu - Agencia Open
Autor URL: http://www.agenciaopen.com

*/

// Flash EcoDicas
function closeEcoDicas() {
    $('div#ecoDica').remove();
}

// jQuery Start
jQuery(document).ready(function () {

    /*
    setInterval( function () {
    $('div').each(function() {
    var o = $(this),
    off = o.offset(),
    p = o.css('position'),
    a = 'relative',
    v = 0.5,
    x = off.top, 
    y = off.left;
					
    if ( p != a )
    {
    o.css('position', a);
    o.css('top', x + 'px');
    o.css('left', y + 'px');
    }
				
    o.css('top', x + v + 'px');
    });
    }, 500 );
    */

    // Flash EcoDicas
    if ($('.home_default').length > 0) {
        /*
        AC_FL_RunContent(
        'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
        'width', '100%',
        'height', '100%',
        'src', 'swf/EcoDica',
        'quality', 'high',
        'pluginspage', 'http://www.adobe.com/go/getflashplayer',
        'align', 'middle',
        'play', 'true',
        'loop', 'true',
        'scale', 'showall',
        'wmode', 'transparent',
        'devicefont', 'false',
        'id', 'EcoDica',
        'bgcolor', '#ffffff',
        'name', 'EcoDica',
        'menu', 'true',
        'allowFullScreen', 'false',
        'allowScriptAccess','sameDomain',
        'movie', 'swf/EcoDica',
        'salign', ''
        ); //end AC code
        */

        var swf = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" ' +
				'width="100%" height="100%" id="EcoDica" align="middle">' +
				'	<param name="allowScriptAccess" value="sameDomain" />' +
				'	<param name="allowFullScreen" value="false" />' +
				'	<param name="wmode" value="transparent" />' +
				'	<param name="movie" value="swf/EcoDica.swf" />' +
				'	<param name="quality" value="high" />' +
				'	<param name="bgcolor" value="#ffffff" />' +
				'<embed src="swf/EcoDica.swf" quality="high" bgcolor="#ffffff" width="100%" height="100%" ' +
				'name="EcoDica" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" ' +
				'pluginspage="http://www.adobe.com/go/getflashplayer" wmode="transparent" />' +
				'</object>';

        var h = $(document).height();
        $('<div id="ecoDica">' + swf + '</div>').prependTo('body').height(h);
    }



    // Tweets
    var tweets = $('div#tweets dl'),
	tweet_sample = $('.tweet_sample'),
	tweet = tweet_sample.clone(),
	tweetLoading = "div#tweets dd.space",
	numTweets = 5,
	account = 'mrvengenharia',
	hashtag = 'ecodica',
	textXPath = 'a.block',
	imgXPath = 'a.pic',
	type = 0,
	next_page = '',
	prev_page = '',
	twitter = 'http://search.twitter.com/search.json',
	since = '', //'2010-03-15',
	until = '2010-04-12',
	query = (account ? '@' + account : '') + '%20%23' + hashtag,
    //	query = '@'+ account,
	api = twitter + '?rpp=' + numTweets +
					(since ? '&since=' + since : '') +
					(until ? '&until=' + until : '') +
					'&q=' + query +
					'&callback=?';

    tweet.removeClass('tweet_sample');
    tweet_sample.remove();

    if (tweets.length)
        loadTweets(api);
    else if ($('ul.twitter_items').length) {
        tweets = $('ul.twitter_items');
        tweetLoading = 'ul.twitter_items li.space';
        type = 1;
        loadTweets(api);
    }

    $('.anterior').click(tweets_prev);
    $('.proxima').click(tweets_next);

    function tweets_prev(e) {
        return tweets_pag($(this), prev_page, e);
    }

    function tweets_next(e) {
        return tweets_pag($(this), next_page, e);
    }

    function tweets_pag(obj, url, e) {
        if (url)
            loadTweets(twitter + url + '&callback=?');

        e.preventDefault();
        return false;
    }

    function loadTweets(url) {
        $('.anterior').addClass('disable');
        $('.proxima').addClass('disable');
        next_page = '';
        prev_page = '';

        $.getJSON(url, function tweetsLoaded(data) {
            var results = data.results;
            if (results) {
                var length = results.length;
                if (length > numTweets)
                    length = numTweets;

                // Clear
                if (length)
                    tweets.children().remove();

                for (var i = 0; i < length; i++) {
                    var tweetData = results[i],
					newTweet = tweet.clone(),
					href = 'http://twitter.com/' + tweetData.from_user + '/status/' + tweetData.id;
                    tweetText = '<strong>' + tweetData.from_user + '</strong> ' + tweetData.text;

                    // Data
                    if (type == 0) {
                        newTweet.children(textXPath).html(tweetText).attr('href', href);
                        newTweet.children(imgXPath).css('background-image', 'url(' + tweetData.profile_image_url + ')').attr('href', href);
                    }
                    else {
                        newTweet.children('div').children('p').children('a').html(tweetText).attr('href', href);
                        newTweet.children('div').children('a').css('background-image', 'url(' + tweetData.profile_image_url + ')').attr('href', href);
                    }

                    // Append & Effects
                    tweets.append(newTweet);
                    newTweet.hide();
                    newTweet.fadeIn();

                    next_page = data.next_page;
                    prev_page = data.previous_page;

                    if (prev_page)
                        $('.anterior').removeClass('disable');

                    if (next_page)
                        $('.proxima').removeClass('disable');
                }
            }
        });
    }



    //Min width
    $(window).bind('resize load', resizeWindow);
    function resizeWindow(e) {
        var screenWidth = $(window).width();
        var largura = (screenWidth <= 1000 ? '998px' : '100%');
        $('#global').css({ width: largura });
    }

    //Count Up
    /*$('#now').each(function(){
    var date = new Date();
    var minutes = date.getMinutes();
    minutes = (minutes == 0 ? '1' : minutes);
    var hours = date.getHours();
    hours = (hours == 0 ? '1' : hours);
    var days = date.getDate();
    //alert(minutes);
    //alert(hours + ' | ' + minutes + ' | ' + days);
    var total = minutes;
    $(this).html(total + '<br />' + 'size');
    });*/


    //Fancybox
    $('#projects .gallery a').fancybox({
        'hideOnContentClick': false,
        'imageScale': true,
        'zoomOpacity': true,
        'frameWidth': 520,
        'frameHeight': 505
    });

    $('#modular .gallery a').fancybox({
        'hideOnContentClick': false,
        'imageScale': true,
        'zoomOpacity': true,
        'frameWidth': 520,
        'frameHeight': 505
    });


    $('a.fancy').fancybox({
        'hideOnContentClick': false,
        'frameWidth': 450,
        'frameHeight': 200
    });


    //Tooltip
    $('a.tooltip').qtip({
        content: false,
        position: {
            corner: {
                target: 'topLeft',
                tooltip: 'bottomRight'
            }
        },
        style: {
            width: 300,
            padding: 5,
            border: {
                width: 7,
                radius: 5
            },
            tip: 'bottomRight',
            name: 'green'
        }
    });


    //sUBSTITUI OS TITULOS POR IMAGEM
    //$('#modular h2').each(function () {

    //var strTitulo = this.innerHTML;
    // this.innerHTML = "<img src=\"image.aspx?Text=" + strTitulo + "&f=" + family + "&s=" + size + "&c=rgb(153, 102, 51)\" alt=\"" + strTitulo + "\" title=\"" + strTitulo + "\" />";

    //});


    // jQuery End
});

//Footstep
function steps() {
    $('#now').each(function () {
        //Requista data
        var date = new Date();
        //Define nome dos meses
        var month = new Array(12);
        month[0] = "January";
        month[1] = "February";
        month[2] = "March";
        month[3] = "April";
        month[4] = "May";
        month[5] = "June";
        month[6] = "July";
        month[7] = "August";
        month[8] = "September";
        month[9] = "October";
        month[10] = "November";
        month[11] = "December";
        //Requisita ano atual
        var year = date.getFullYear();
        //Define quantos segundos se passaram ate o 1º dia do mes atual
        var renew = Date.parse(month[date.getMonth()] + ' 1, ' + year);
        //Define quantos segundos se passaram ate o exato momento
        var since = date.getTime();
        //Diferenca em segundos de agora para o 1º dia do mes
        var today = Math.round((since - renew) / 1000);

        var total = Math.round(today * 4.2);
        total = String(total);
        //Case
        if (total <= 999999) {
            metric = 'litros';
            total = addChar(total, '.');
            //alert(total + ' ' + metric);
        } else if (total > 1000000 && total <= 1999998) {
            metric = 'litros';
            total = addChar(total, ',');
            //total = total.substr(0,5);
            //alert('!');
        } else if (total > 1999998 && total <= 9999990) {
            metric = 'litros';
            total = addChar(total, '.');
            //total = total.substr(0,5);
        } else {
            metric = 'litros';
            total = addChar(total, '.');
            //total = total.substr(0,6);
        }

        //Adicionando caracter
        function addChar(nStr, nType) {
            nStr += '';
            x = nStr.split('.');
            x1 = x[0];
            x2 = x.length > 1 ? '.' + x[1] : '';
            var rgx = /(\d+)(\d{3})/;
            while (rgx.test(x1)) {
                x1 = x1.replace(rgx, '$1' + nType + '$2');
            }
            return x1 + x2;
        }

        //comma = comma.substr(0,6);
        //alert(addCommas(comma));

        //Debug
        //$('#teste').html('since (ate hoje): ' + since + '<br />renew (1/1970 ate ' + date.getMonth() + '/' + date.getFullYear() + '): ' + renew + '<br />today: ' + today + ' segundos <br /> data: ' + Date() + '<br />litros (total de segundos x 4.2L): ' + today*4.2  + ' | arrendondado: ' + Math.round(238095*4.2));
        $(this).html(total + '<br />' + metric);
    });
    setTimeout('steps()', 1000);
}

steps();


//contador arvores
function contArvores() {
    $('#arvores').each(function () {

        var dataAtual = new Date();
        //Data inicial fixa
        var dataInicial = new Date("Tue Jan 25 2011 00:00:00 GMT-0200");
        //var dif = parseInt((dataAtual - dataInicial) / 600000);
        var dif = parseInt((dataAtual - dataInicial) / 300000);

        //O total de arvores plantadas iniciou já com 55000 a pedido da MRV
        dif = dif + 55000;
        dif = addChar(dif, '.');

        //Adicionando caracter
        function addChar(nStr, nType) {
            nStr += '';
            x = nStr.split('.');
            x1 = x[0];
            x2 = x.length > 1 ? '.' + x[1] : '';
            var rgx = /(\d+)(\d{3})/;
            while (rgx.test(x1)) {
                x1 = x1.replace(rgx, '$1' + nType + '$2');
            }
            return x1 + x2;
        }

        $(this).html(dif + '<br /> &#225rvores');
    });
    //atualiza a cada 1 segundo
    setTimeout('contArvores()', 1000);
}

contArvores();


function UrlBusca() {
    var strCidade = "", strBairro = "", strEstado = "";

    if (document.getElementById("ctl00_ddlEstados")) {
        strEstado = document.getElementById("ctl00_ddlEstados").value;
    }
    if (document.getElementById("ctl00_ddlCidades")) {
        strCidade = document.getElementById("ctl00_ddlCidades").value;
    }
    if (document.getElementById("ctl00_ddlBairros")) {
        strBairro = document.getElementById("ctl00_ddlBairros").value;
    }
    if (document.getElementById("ctl00_ddlCidades")) {
        if (document.getElementById("ctl00_ddlCidades").value == "0") {
            alert('Selecione uma cidade para efetuar a busca!');
            return false;
        }
        else {
            if (window.location.href.indexOf("opencorporate") > -1 || window.location.href.indexOf("localhost") > -1) {
                window.open("http://imoveis.opencorporate.com.br/busca.aspx?w=www.mrvsustentavel.com.br&e=" + strEstado + "&c=" + strCidade + "&b=" + strBairro);
            }
            else {
                window.open("http://imoveis.mrv.com.br/busca.aspx?w=www.mrvsustentavel.com.br&e=" + strEstado + "&c=" + strCidade + "&b=" + strBairro);
            }

        }
    }
}

function mask(isNum, event, field, mask, maxLength) {
    var keyCode;
    if (event.srcElement)
        keyCode = event.keyCode;
    else if (event.target)
        keyCode = event.which;
    var maskStack = new Array();
    var isDynMask = false;
    if (mask.indexOf('[') != -1)
        isDynMask = true;
    var length = mask.length;
    for (var i = 0; i < length; i++)
        maskStack.push(mask.charAt(i));
    var value = field.value;
    var i = value.length;
    if (keyCode == 0 || keyCode == 8)
        return true;
    //código adaptado para aceitar X (maiúsculo) ou x (minúsculo), além de números
    if (isNum && (keyCode < 48 || keyCode > 57) && (keyCode != 88) && (keyCode != 120))
        return false;
    if (!isDynMask && i < length) {
        if (maskStack.toString().indexOf(String.fromCharCode(keyCode)) != -1 && keyCode != 8) {
            return false;
        } else {
            if (keyCode != 8) {
                if (maskStack[i] != '#') {
                    var old = field.value;
                    field.value = old + maskStack[i];
                }
            }
            if (autoTab(field, keyCode, length)) {
                if (!document.layers) {
                    return true;
                } else if (keyCode != 8) {
                    field.value += String.fromCharCode(keyCode);
                    return false;
                } else {
                    return true;
                }
            } else {
                return false;
            }
        }
    } else if (isDynMask) {
        var maskChars = "";
        for (var j = 0; j < maskStack.length; j++)
            if (maskStack[j] != '#' && maskStack[j] != '[' && maskStack[j] != ']')
                maskChars += maskStack[j];
    var tempValue = "";
    for (var j = 0; j < value.length; j++) {
        if (maskChars.indexOf(value.charAt(j)) == -1)
            tempValue += value.charAt(j);
    }
    value = tempValue + String.fromCharCode(keyCode);
    if (maskChars.indexOf(String.fromCharCode(keyCode)) != -1) {
        return false;
    } else {
        var staticMask = mask.substring(mask.indexOf(']') + 1);
        var dynMask = mask.substring(mask.indexOf('[') + 1, mask.indexOf(']'));
        var realMask = new Array;
        if (mask.indexOf('[') == 0) {
            var countStaticMask = staticMask.length - 1;
            var countDynMask = dynMask.length - 1;
            for (var j = value.length - 1; j >= 0; j--) {
                if (countStaticMask >= 0) {
                    realMask.push(staticMask.charAt(countStaticMask));
                    countStaticMask--;
                }
                if (countStaticMask < 0) {
                    if (countDynMask >= 0) {
                        if (dynMask.charAt(countDynMask) != '#') {
                            realMask.push(dynMask.charAt(countDynMask));
                            countDynMask--;
                        }
                    }
                    if (countDynMask == -1) {
                        countDynMask = dynMask.length - 1;
                    }
                    realMask.push(dynMask.charAt(countDynMask));
                    countDynMask--;
                }
            }
        }
        var result = "";
        var countValue = 0;
        while (realMask.length > 0) {
            var c = realMask.pop();
            if (c == '#') {
                result += value.charAt(countValue);
                countValue++;
            } else {
                result += c;
            }
        }
        field.value = result;
        if (maxLength != undefined && value.length == maxLength) {
            var form = field.form;
            for (var i = 0; i < form.elements.length; i++) {
                if (form.elements[i] == field) {
                    field.blur();
                    //if alterado para quando a máscara for utilizada no último campo, não dê mensagem de erro quando tentar colocar o foco no "Salvar"
                    //if (form.elements[i + 1] != null)										 
                    if ((form.elements[i + 1] != null) && (form.elements[i + 1].name != "METHOD"))
                        form.elements[i + 1].focus();
                    break;
                }
            }
        }
        return false;
    }
} else {
    return false;
}
function autoTab(field, keyCode, length) {
    var i = field.value.length;
    if (i == length - 1) {
        field.value += String.fromCharCode(keyCode);
        var form = field.form;
        for (var i = 0; i < form.elements.length; i++) {
            if (form.elements[i] == field) {
                field.blur();
                //if alterado para quando a máscara for utilizada no último campo, não dê mensagem de erro quando tentar colocar o foco no "Salvar"
                //if (form.elements[i + 1] != null)
                if ((form.elements[i + 1] != null) && (form.elements[i + 1].name != "METHOD"))
                    form.elements[i + 1].focus();
                break;
            }
        }
        return false;
    } else {
        return true;
    }
}
}

function addLegenda(legenda) {
    var legenda = legenda;
    $(document).ready(function () {
        $('#fancy_title_main div').html(legenda);
    })
};

