/*
 * jqModal - Minimalist Modaling with jQuery
 *   (http://dev.iceburg.net/jquery/jqModal/)
 *
 * Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net>
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * $Version: 03/01/2009 +r14
 */
(function($){$.fn.jqm=function(o){var p={overlay: 50,overlayClass: 'jqmOverlay',closeClass: 'jqmClose',trigger: '.jqModal',ajax: F,ajaxText: '',target: F,modal: F,toTop: F,onShow: F,onHide: F,onLoad: F};return this.each(function(){if(this._jqm)return H[this._jqm].c=$.extend({},H[this._jqm].c,o);s++;this._jqm=s;H[s]={c:$.extend(p,$.jqm.params,o),a:F,w:$(this).addClass('jqmID'+s),s:s};if(p.trigger)$(this).jqmAddTrigger(p.trigger);});};$.fn.jqmAddClose=function(e){return hs(this,e,'jqmHide');};$.fn.jqmAddTrigger=function(e){return hs(this,e,'jqmShow');};$.fn.jqmShow=function(t){return this.each(function(){t=t||window.event;$.jqm.open(this._jqm,t);});};$.fn.jqmHide=function(t){return this.each(function(){t=t||window.event;$.jqm.close(this._jqm,t)});};$.jqm = {hash:{},open:function(s,t){var h=H[s],c=h.c,cc='.'+c.closeClass,z=(parseInt(h.w.css('z-index'))),z=(z>0)?z:3000,o=$('<div></div>').css({height:'100%',width:'100%',position:'fixed',left:0,top:0,'z-index':z-1,opacity:c.overlay/100});if(h.a)return F;h.t=t;h.a=true;h.w.css('z-index',z);if(c.modal) {if(!A[0])L('bind');A.push(s);} else if(c.overlay > 0)h.w.jqmAddClose(o); else o=F;h.o=(o)?o.addClass(c.overlayClass).prependTo('body'):F;if(ie6){$('html,body').css({height:'100%',width:'100%'});if(o){o=o.css({position:'absolute'})[0];for(var y in {Top:1,Left:1})o.style.setExpression(y.toLowerCase(),"(_=(document.documentElement.scroll"+y+" || document.body.scroll"+y+"))+'px'");}}if(c.ajax) {var r=c.target||h.w,u=c.ajax,r=(typeof r == 'string')?$(r,h.w):$(r),u=(u.substr(0,1) == '@')?$(t).attr(u.substring(1)):u;r.html(c.ajaxText).load(u,function(){if(c.onLoad)c.onLoad.call(this,h);if(cc)h.w.jqmAddClose($(cc,h.w));e(h);});} else if(cc)h.w.jqmAddClose($(cc,h.w));if(c.toTop&&h.o)h.w.before('<span id="jqmP'+h.w[0]._jqm+'"></span>').insertAfter(h.o);	(c.onShow)?c.onShow(h):h.w.show();e(h);return F;},close:function(s){var h=H[s];if(!h.a)return F;h.a=F;if(A[0]){A.pop();if(!A[0])L('unbind');}if(h.c.toTop&&h.o)$('#jqmP'+h.w[0]._jqm).after(h.w).remove();if(h.c.onHide)h.c.onHide(h);else{h.w.hide();if(h.o)h.o.remove();} return F;},params:{}};var s=0,H=$.jqm.hash,A=[],ie6=$.browser.msie&&($.browser.version == "6.0"),F=false,i=$('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity:0}),e=function(h){if(ie6)if(h.o)h.o.html('<p style="width:100%;height:100%"/>').prepend(i);else if(!$('iframe.jqm',h.w)[0])h.w.prepend(i); f(h);},f=function(h){try{$(':input:visible',h.w)[0].focus();}catch(_){}},L=function(t){$()[t]("keypress",m)[t]("keydown",m)[t]("mousedown",m);},m=function(e){var h=H[A[A.length-1]],r=(!$(e.target).parents('.jqmID'+h.s)[0]);if(r)f(h);return !r;},hs=function(w,t,c){return w.each(function(){var s=this._jqm;$(t).each(function() {if(!this[c]){this[c]=[];$(this).click(function(){for(var i in {jqmShow:1,jqmHide:1})for(var s in this[i])if(H[this[i][s]])H[this[i][s]].w[i](this);return F;});}this[c].push(s);});});};})(jQuery);
$(document).ready(function(){
    $('#dialog').jqm();
    tooltip();
    mobileAjuda();
    $("#menu li a:not(.ativo)").fadeOut(1000);
    /*$("#menu li").hover(
        function(){
            $(this).children("a:not(.ativo)").stop().fadeTo('slow', 1);
        },
        function() {
            $(this).children("a:not(.ativo)").fadeOut('fast');
        }
    );*/
    $("#menu li").bind({
  click:function(){
      var bt_click = $(this).children("A");
      if (bt_click.css('display') == "none") {
    bt_click.fadeTo('fast', 1);
    location.href = bt_click.attr('href');
      }
  },
  mouseenter:function(){
            $(this).children("a:not(.ativo)").stop().fadeTo('slow', 1);
        },
  mouseleave:function() {
            $(this).children("a:not(.ativo)").fadeOut('fast');
        }
    });
    $("#sosiniciante_submenu a:not(.ativo)").fadeOut(1000);
    $("#sosiniciante_submenu li").hover(
        function(){
            $(this).children("a:not(.ativo)").stop().fadeTo('slow', 1);
        },
        function() {
            $(this).children("a:not(.ativo)").fadeOut('slow');
        }
    );
});
function tooltip(){
    $(".feeds li").hover(function(){
  $(this).find('.tooltip').fadeIn("fast");
    },
    function(){
  $(this).find('.tooltip').fadeOut("fast");
    });
}
function mobileAjuda(){
    $(".ajuda").toggle(
  function() {
      $(".box-ajuda").fadeIn(300); // ou slideDown()
  },
  function() {
      $(".box-ajuda").fadeOut(300); // ou slideUp()
  }
    );
}



function showFadingIEFix(el) {
  if ($.browser.msie || $.browser.mozilla) { el.show(); }
  else { el.fadeTo('slow', 1); }
};


var cmbPerson_out = false, cmbPerson_head, interval;
$(document).ready(function(){
  cmbPerson_head = $('#cmbPerson .head');
  cmbPerson_head.toggle(
    function() { cmbPerson_out = true;
      showFadingIEFix($(this).parent().children('.listagem'));
      $(this).parent().addClass('personAtivo');
    },
    function(){
      cmbPerson_out = false;
      $(this).parent().children('.listagem').stop().hide();
      $(this).parent().removeClass('personAtivo');
    }
  );

  $('#cmbPerson').bind("mouseleave",function(){
    if(cmbPerson_out){
      cmbPerson_out = false;
      interval = setTimeout('cmbPerson_out_click();', 200);
    }
  });
});
function cmbPerson_out_click(){
  cmbPerson_head.click();
}


var findbyphone = {
  'catalog': {
    'Apple': {
      'IPhone 3G': 'iPhone OS',
      'IPhone 3GS': 'iPhone OS'
    },
    'BlackBerry': {
      'Curve 8300': 'Blackberry',
      'Pearl 8100': 'Blackberry',
      '8310': 'Blackberry',
      '8110': 'Blackberry',
      '9000 - Bold': 'Blackberry',
      '9500- Storm': 'Blackberry',
      '8900 - Javelin': 'Blackberry',
      '8520 - Gemini': 'Blackberry',
      '8220': 'Blackberry',
      '9700': 'Blackberry'
    },
    'HP': {
      'iPaq hw6945': 'Windows Mobile',
      'iPaq 510': 'Windows Mobile',
      'iPaq 910': 'Windows Mobile'
    },
    'HTC': {
      'Diamond': 'Windows Mobile',
      'P3301': 'Windows Mobile',
      'P3401': 'Windows Mobile',
      'P3450': 'Windows Mobile',
      'P4351': 'Windows Mobile',
      'S621': 'Windows Mobile',
      'S711': 'Windows Mobile',
      'T2223': 'Windows Mobile',
      'Touch Dual': 'Windows Mobile',
      'Touch 2': 'Windows Mobile',
      'TyTN II': 'Windows Mobile'
    },
    'LG': {
      'GW550 (Times)': 'Windows Mobile'
    },
    'Motorola': {
      'A3100': 'Windows Mobile',
      'Milestone': 'Android',
      'Q': 'Windows Mobile',
      'Q11': 'Windows Mobile'
    },
    'Nokia': {
      'E61i': 'Symbian',
      'E63': 'Symbian',
      'E66': 'Symbian',
      'E71': 'Symbian',
      'E75': 'Symbian',
      'N76': 'Symbian',
      'N81 8GB': 'Symbian',
      'N85': 'Symbian',
      'N95': 'Symbian',
      'N95 8 GB': 'Symbian',
      'N96': 'Symbian',
      'N97': 'Symbian'
    },
    'Palm': {
      'CENTRO': 'Windows Mobile'
    },
    'Samsung': {
      'B7320 Omnia Pró': 'Windows Mobile',
      'i617': 'Windows Mobile'
    }
  },
  'mapping': {
    'Android': 'android',
    'Blackberry': 'blackberry',
    'MAC': 'iphone',
    'Palm': 'palm',
    'Symbian': 'symbian',
    'Windows Mobile': 'windows-mobile'
  },
  'tBrand': null, 'tDevice': null,
  'selects': null, 'origHeight': 0, 'comboOpened': null,
  'result': null, 'resultHeight': 0,

  'start': function () {
    if (!$('#box-mobile .findbyphone .hotarea')[0]) { return; }
    $('#box-mobile .findbyphone .hotarea').click(findbyphone.toggle);
    findbyphone.tMain = $('#box-mobile .findbyphone');
    findbyphone.selects = $('#box-mobile .findbyphone .opts');
    findbyphone.origHeight = findbyphone.selects.height();
    $('#box-mobile .findbyphone .combo').click(findbyphone.openOpts);

    findbyphone.generateList(findbyphone.catalog, $('#brandList')[0]);
    $('#brandList li a').click(findbyphone.chooseBrand);
    $('#box-mobile .findbyphone .result span').click(findbyphone.chooseSystem);
    $('#box-mobile .findbyphone .opts input').click(findbyphone.chooseSystem);

    findbyphone.selects.height(0)[0].style.position = 'static';
    findbyphone.result = $('#box-mobile .findbyphone .result');
    findbyphone.resultHeight = findbyphone.result.height();
    findbyphone.result.slideUp(1, function() { findbyphone.result[0].style.position = 'static'; });
  },
  'toggle': function (e) {
    return findbyphone[(findbyphone.tMain.hasClass('opened')) ? 'close' : 'open']();
  },
  'open': function() { findbyphone.tMain.addClass('opened');
    var targHeight = (findbyphone.tBrand === null) ? '31px' : findbyphone.origHeight +'px';
    findbyphone.selects.stop(true).animate({'height': targHeight}, 'normal');
  },
  'close': function() {
    if (findbyphone.comboOpened) { return findbyphone.closeOpts(findbyphone.close); }
    findbyphone.tMain.removeClass('opened');
    findbyphone.selects.stop(true).animate({'height': 0}, 'normal');
  },

  'openOpts': function (e) {
    var nome = ($(this).hasClass('combo1')) ? 'sublist1' : 'sublist2';
    var openNew = $('#box-mobile .findbyphone .'+ nome)
    if (findbyphone.comboOpened) { var closing = 0;
      if (findbyphone.comboOpened[0] == openNew[0]) { closing = 1; }
      findbyphone.closeOpts(); if (closing) { return; }
    }
    openNew.stop().fadeTo('normal', 1, function () { this.style.filter = ''; });
    findbyphone.comboOpened = openNew;
  },
  'closeOpts': function (callback) { if (!findbyphone.comboOpened) { return; }
    findbyphone.comboOpened.stop().fadeOut('fast', callback); findbyphone.comboOpened = null;
  },

  'generateList': function (tList, whereToPut) {
    while (whereToPut.childNodes.length) { whereToPut.removeChild(whereToPut.childNodes[0]); }
    var tL, tA, node; for (node in tList) {
      tL = document.createElement('li'); tA = document.createElement('a');
      tA.innerHTML = node; tL.appendChild(tA); whereToPut.appendChild(tL);
    }
  },

  'chooseBrand': function () { findbyphone.tBrand = this.innerHTML; findbyphone.tDevice = null;
    findbyphone.generateList(findbyphone.catalog[findbyphone.tBrand], $('#deviceList')[0]);
    $('#deviceList li a').click(findbyphone.chooseDevice);

    var tE = $('#brandName')[0]; tE.innerHTML = this.innerHTML;
    $('#deviceName')[0].innerHTML = 'Selecione o aparelho';
    findbyphone.closeOpts(); findbyphone.open();
    findbyphone.result.slideUp();
  },
  'chooseDevice': function () { findbyphone.tDevice = this.innerHTML;
    var tE = $('#deviceName')[0]; tE.innerHTML = this.innerHTML;
    findbyphone.closeOpts(); findbyphone.showResult();
  },
  'chooseSystem': function () {
    if (findbyphone.tDevice == null) { return; }
    var system = $('#box-mobile .findbyphone .result span')[0].innerHTML;
    selecionaSistemaOperacional(null, findbyphone.mapping[system]);
  },
  'showResult': function () {
    var system = findbyphone.catalog[findbyphone.tBrand][findbyphone.tDevice];
    $('#box-mobile .findbyphone .result span')[0].innerHTML = system;
    findbyphone.result.slideDown('slow');
  }
}; $(findbyphone.start);


var createNamedElement=function (){}; //Cria elemento com "name" -- cross-browser
(function () {
  try {
    var nE=document.createElement('<div name="foo">'); //Jeito esquisitão do IE criar objetos com "name"
    if (nE.tagName != 'DIV' || nE.name != 'foo') { /* força o "catch" */ throw 'create element error'; }
    //Se passou do passo acima, estamos em um navegador que usa o "jeito IE", então criamos a função de acordo
    createNamedElement = function (tT, tN) {
      return document.createElement('<'+ tT +' name="'+ tN +'"></'+ tT +'>');
    };
  } catch (e) { //Forma bonita e funcional, como deveria sempre ser
    createNamedElement = function (tT, tN) { var newEl;
      return ((newEl=document.createElement(tT)) && (newEl.name=tN) && newEl);
    };
  }
})();
function cTN(tV) { return (tV && document.createTextNode && document.createTextNode(tV)); }
function cE(tN, tPs, tC) { // newCreateElement -- <str tagName> [, obj tProperties] [, str/arr conteúdo]
  if (!tN || !document.createElement) { return false; } var nE, tER, i, n, tP;
  if (arguments.length == 1) { return document.createElement(tN); } //criação simples
  if (arguments.length == 2) { tC=tPs; tPs={}; } //Parãmetros 1 e 3.
  nE=(tPs.name) ? createNamedElement(tN, tPs.name) : document.createElement(tN);
  for (i in tPs) { //Há um tratamento especial para o "class" e "className".
    if (i == 'class' || i == 'className') { nE.className=tPs[i]; }
    else { nE.setAttribute(i, tPs[i]); } //Os outros usam o setAttribute padrão
  }
  if (tC) { if (!(tC instanceof Array)) { /* DRY! */ tC=[tC]; }
    for (i=0, n=tC.length; i<n; i++) {
      nE.appendChild( (typeof(tC[i])=='string') ? cTN(tC[i]) : tC[i] );
    }
  }
  return nE;
}



function getTwitterBox() { var tI = $('#box-twitter ul:first');
  return tI.length ? tI : false;
}
function showTweets(tweetsList) { var tB = getTwitterBox(); if (!tB) { return; }
/*
<li class="li-twitter">
    <div class="img-twitter">
        <a href="#" target="_blank"><img src="#" alt="" /></a>
    </div>
    <div class="txt-twitter">
        <h3><a href="#" target="_blank">#NOME#:</a></h3>
        <p class="tw-twitter"><a href="#" target="_blank">#TEXTO#</a></p>
        <p class="time-twitter">#DATA E HORA#</p>
    </div>
</li>
*/
  var nLI, user, userURL, time;
  var n = 4, i = 0, cur; tB.empty(); while (i<n) { cur = tweetsList[i++];
    user = cur.from_user; userURL = 'http://twitter.com/'+ user;
    time = twitterSearch.friendlyTime(cur.minutes_ago);
    nLI = cE('li', {'class': 'li-twitter'},
      cE('a', {'target': '_blank', 'href': userURL}, [
        cE('div', {'class': 'img-twitter'},
          cE('img', {'width': 48, 'height': 48, 'src': cur.profile_image_url}, '')
        ),
        cE('div', {'class': 'txt-twitter'}, [
          cE('h3', user),
          cE('p', {'class': 'tw-twitter'}, cur.text),
          cE('p', {'class': 'time-twitter'}, time)
        ])
      ])
    );
    tB[0].appendChild(nLI);
  }
}
var twitterSearch = {
  'confirmStart': getTwitterBox,
  'finishedCallback': showTweets,
  'resultPagesSize': 4,
  'timeout': 10, //segundos
  'limitlanguage': 'pt', //se quiser tudo, defina como "false" (sem aspas)
  'hashtags': [
                '#Apps', '#iPhone', '#Windowsmobile', '#Blackberry', '#Bberry',
                '#Android', '#Symbian', '#SPFGeek', '#Socialmedia', '#worldcup',
                '#nokia', '#iPad', '#ovi', '#appstore'
              ],
  'searchStrings': [],
  'profiles': ['oiapplicativos'],
  'blacklist': [],

  'now': new Date().getTime(), 'timedout': false, 'returned': 0, 'targN': 0,

  'urlSearch': 'http://search.twitter.com/search.json?rpp=%d&callback=twitterSearch.gotResultFromSearch&q=%s',
  'urlProfile': 'http://twitter.com/status/user_timeline/%s.json?count=%d&callback=twitterSearch.gotResultFromTimeLine',
  'searchInfo': [], 'tweets': [], 'tweetIDs': [],

  'start': function () {
    if (twitterSearch.hashtags.length) {
      twitterSearch.searchStrings.unshift(twitterSearch.hashtags.join(' OR '));
    }
    if (twitterSearch.limitlanguage) { twitterSearch.urlSearch += '&lang='+ twitterSearch.limitlanguage; }
    twitterSearch.targN = twitterSearch.searchStrings.length + twitterSearch.profiles.length;
    if (!twitterSearch.finishedCallback || twitterSearch.targN == 0) { return false; }

    var n1 = twitterSearch.searchStrings.length, n2 = twitterSearch.profiles.length, tB = $('body')[0];
    while (n1--) {
      twitterSearch.addJSToBody(tB, twitterSearch.urlSearch, twitterSearch.searchStrings[n1]);
    }
    while (n2--) {
      twitterSearch.addJSToBody(tB, twitterSearch.urlProfile, twitterSearch.profiles[n2]);
    }
    twitterSearch.timeout = window.setTimeout(twitterSearch.toolong, twitterSearch.timeout *1000);
  },
  'addJSToBody': function (parent, tURLPattern, tItem, rnd) { var nS, tSrc;
    nS = document.createElement('script'); nS.type='text/javascript';
    tSrc = tURLPattern.replace('%s', encodeURIComponent(tItem));
    tSrc = tSrc.replace('%d', twitterSearch.resultPagesSize);
    if (rnd) { tSrc += '&rnd='+ Math.round(Math.random() *10000); }
    nS.src = tSrc; parent.appendChild(nS);
  },
  'toolong': function () { //mimimi
    twitterSearch.timedout = true; twitterSearch.joinSearches();
  },
  'gotResultFromTimeLine': function (searchInfo) {
    for (var i in searchInfo) { //normalização
      searchInfo[i].from_user = searchInfo[i].user.screen_name;
      searchInfo[i].profile_image_url = searchInfo[i].user.profile_image_url;
    }
    twitterSearch.gotResult(searchInfo);
  },
  'gotResultFromSearch': function (searchInfo) {
    twitterSearch.gotResult(searchInfo.results);
  },
  'gotResult': function(resultList) { if (twitterSearch.timedout) { return; }
    twitterSearch.searchInfo[twitterSearch.searchInfo.length] = resultList;
    if (++twitterSearch.returned == twitterSearch.targN) {
      window.clearTimeout(twitterSearch.timeout); twitterSearch.joinSearches();
    }
  },

  'joinSearches': function() {
    var n = twitterSearch.searchInfo.length, curSearchInfo, nn, curResult, curTS;
    if (twitterSearch.blacklist.length) {
      var tERText = '^(.*[^a-zA-Z0-9])?('+ twitterSearch.blacklist.join('|') +')([^a-zA-Z0-9].*)?$';
      var tER = new RegExp(tERText, 'im');
    }

    while (n--) { curSearchInfo = twitterSearch.searchInfo[n]; nn = curSearchInfo.length;
      while (nn--) { curResult = curSearchInfo[nn];
        if (!twitterSearch.tweetIDs[curResult.id]) {
          twitterSearch.tweetIDs[curResult.id] = true;
          if (tER && tER.test(curResult.text)) { continue; }
          curTS = Date.parse(curResult.created_at);
          curResult.minutes_ago = Math.floor((twitterSearch.now -curTS) /1000 /60);
          twitterSearch.tweets[twitterSearch.tweets.length] = curResult;
        }
      }
    } twitterSearch.tweets.sort(twitterSearch.compareTweets);

    twitterSearch.finishedCallback(twitterSearch.tweets);
  },
  'compareTweets': function (a, b) { return (a.minutes_ago -b.minutes_ago); },

  'friendlyTime': function (minutes) { var s, h, d;
    if (minutes < 60) {
      if (minutes < 1) { return 'uns segundos atrás'; }
      s = (minutes > 1) ? 's' : '';
      return minutes +' minuto'+ s +' atrás';
    } else if (minutes < 60 *24) {
      var h = Math.floor(minutes /60), s = (h > 1) ? 's' : '';
      return Math.floor(minutes /60) +' hora'+ s +' atrás';
    } else { var dias = Math.floor(minutes /60 /24);
      if (dias == 1) { return 'ontem'; }
      else if (dias == 2) { return 'anteontem'; }
      else if (dias > 25) { return 'muito tempo atrás'; }
      return dias +' dias atrás';
    }
  }
}; $(twitterSearch.start);
