/*
 * 
 * WEBEUPHONY (c) 2011
 * 
 * Custom javascripts
 */

/**
 * Logout displaying
 */
$(document).ready(function(){
  $('#breadcumb').hover(function(){
    $(this).find('.logoutHidden').show();
  }, function(){
    $(this).find('.logoutHidden').hide();
  });
});

/**
 * Place subscription alert
 */
function placeSbscrNotice(title,text){
  var dialogTemplate = '<div id="b-dialog-overlay"><!-- --></div>' +
                       '<div id="b-dialog"><div class="dialog-holder">' +
                        '<h2>'+ title +'</h2>'+
                        '<div class="contentarea">'+ text +'</div>'+
                       '</div></div>';
  $('body').append(dialogTemplate);
  var scrTop = $('#b-dialog-overlay').offset().top + ($('html').height() / 2) - ($('#b-dialog').height() / 2);
  $('#b-dialog').css({top:scrTop});
  setTimeout("$('#b-dialog').fadeOut('slow', function(){$('#b-dialog, #b-dialog-overlay').remove()});", 4000);
}
$(document).ready(function(){
  $('#b-dialog, #b-dialog-overlay').live('click',function(){
    $('#b-dialog, #b-dialog-overlay').remove();
  });
});

/**
 * CUSTOM Comboboxes
 */
function customCombo(){
  $('.b-customCombobox').each(function(){
    if ( $(this).find('.b-customComboFake').size() == '0' ){
      $(this).append('<ul class="b-customComboFake" />');
      var newComboWrapper = $(this).find('.b-customComboFake');
      var nativeSelect = $(this).find('select');
      var sel = '';
      var items = new Array();
      var callObj = $(this).prev('.privacyLock');
      callObj.attr('title',nativeSelect.find('option[selected="selected"]').text());
      items = $(this).find('option').clone();
      for (i=0; i < $(items).size(); i++) {
        if ( $(items[i]).attr('selected') ){
          sel = ' selected';
        } else {
          sel = '';
        }
        newComboWrapper.append('<li class="comboItem'+sel+'">'+$(items[i]).html()+'</li>')
      }
      // Change selected item
      $(this).find('.comboItem').live('click', function(){
        if ( !$(this).hasClass('selected') ) {
          $(this).parent().find('.selected').removeClass('selected');
          $(this).addClass('selected');
          var newValue = $(this).text();
          callObj.attr('title',newValue);
          nativeSelect.find('option').removeAttr('selected').each(function(){
            if( $(this).text() == newValue ){
              $(this).attr('selected',true);
              nativeSelect.change();
              //console.log($(this))
            }
          });
        }
      });
    }
  });

}
$(document).ready(function(){
  customCombo();

  $('.b-customComboboxOut').live('mouseleave',function(){
    $(this).find('.privacyLockOpened').click();
  });

  $('.privacyLock').live('click',function(){
    $(this).toggleClass('privacyLockOpened').parent().find('.b-customComboFake').toggle();
  });

});

/**
 * CUSTOM SCRIPT LOAD EVERYTHING
 */
$(document).ready(function(){
    $("#create_account_btn").colorbox({width:'380px',height:'520px'});
    $("#login_btn").colorbox({width:'380px',height:'277px'});
});

/**
 * Hint input 
 * 
 * Use with CSS 
 * .hintTmp{ color:#999; font-style:italic; }
 * 
 * Example: 
 * <input id="search_place" class="hint" type="text" name="place" value="Name of Place" />
 * 
 */
$(document).ready(function(){
  $(".hint").each(function(){
    var defVal = $(this).val();
    $(this).attr('title',defVal).addClass('hintTmp');
    $(this).focus(function(){
        if ( $(this).val() == $(this).attr('title') ){
            $(this).val("").removeClass("hintTmp");
        }
    }).blur(function(){
        if ( !$(this).val() ){
            $(this).val($(this).attr('title')).addClass('hintTmp');
        }
    });
  });

  $('.prev-fake').click(function(){
    $(this).next().find('.prev').click();
  });
  $('.next-fake').click(function(){
    $(this).prev().find('.next').click();
  });
//  $('.b-sliderWrapper').scrollable({circular:true});
});

/**
 * 
 * Comment box
 * 
 */
$(document).ready(function(){
  // Initialize
  $(".b-commentForm textarea").val("Write a comment...");
  
  // Add focus handler
  $(".b-commentForm textarea").live('focusin', function(){
    // Clear value
    if ($(this).val() == "Write a comment...") {
      $(this).val("");
    }
    // Expand form
    $(".b-commentForm").has(this).addClass("expanded");
  }).live('focusout', function(){
    if ($(this).val().length == 0) {
      $(this).val("Write a comment...");
      $(".b-commentForm").has(this).removeClass("expanded");
    }
  });
  // Comment button
  $(".comment-button").live("click", function(){
    var commentBox = $(".b-blogSingle").has(this).find(".b-comments");
    commentBox.show();
    commentBox.find(".b-commentForm textarea").focus();
  });

  // Submit comment form via Ajax
  $(".b-commentForm").live('submit',function(){
    var blog_post_element = $(this).find("input:hidden").get(1);
    var blog_post_id = $(blog_post_element).val();
    var form = $(this);
    $(this).ajaxSubmit({
      type: 'POST',
      beforeSubmit: function(formData, jqForm, options){
        $(form).find("textarea").html('<div class="ui-pages-loading">&nbsp;</div>');
      },
      success: function(data, statusText, xhr, $form){
        $(form).parent().find(".b-commentsList").append(data);
        $(form).find("textarea").val('');
        $(form).find("textarea").focusout();
      }
    }); 
    return false;
  });

  $(".commentLoadLink").live('click',function(){
    $('.b-commentsList').has(this).load(this.href);
    return false;
  });

});

// ------------------------------------------------
// Splash page slider
$(document).ready(function(){

  sliderSwitcher();

  $('.b-splashSliderBrowse a').live('click',function(){
    var obj = $(this).attr('href');
    $('.b-splashSlider .item').fadeOut('slow');
    $(obj).fadeIn();
    $(this).parent().parent().find('li').removeClass('active');
    $(this).parent().addClass('active');
  });

});

function stopSliderSwitcher(){
  clearTimeout(t);
}

function sliderSwitcher(){
  var curPos = $('.b-splashSliderBrowse').find('.active');
  if ( curPos.next('li').size() ) {
    curPos.next('li').find('a').click();
  } else {
    $('.b-splashSliderBrowse li:first').find('a').click();
  }
  t=setTimeout("sliderSwitcher();",3000);
}

/**
 * Create DOM elemet
 *
 * @param string type Element type(tag name)
 * @param array attrs An associative array of attrs and values
 * @param string content Inner html content
 */
function createElement(type, attrs, content) {
 /* type: string tag name
  * content: string element content
  * attrs: associative array of attrs and values
  */
  elem = '<' + type + '></' + type + '>'
  e = jQuery(elem).attr(attrs)
  e.append(content)
  return e
};


/**
 * 
 * Compliment box
 * 
 */
$(document).ready(function(){

  $(".signin").click(function(e) {
    e.preventDefault();
    $("#authForm").toggle();
    $(".signin").toggleClass("menu-open");
  });
  $("#authForm").mouseup(function() {
    return false
  });
  $(document).mouseup(function(e) {
    if($(e.target).parent("a.signin").length==0) {
      $(".signin").removeClass("menu-open");
      $("#authForm").hide();
    }
  });

  // Control compliment box
  $(".compliment-button").live("click", function(){
    var id = $(this).attr("id");
    $("."+id+"-comment-rply").slideUp(0);
    $("."+id+"-compliment-rply").slideToggle(0);
    $(this).toggleClass("active");
    return false;
  });

  // Link a with form submit
  $(".ajax-form-submit").live('click',function(){
    $(this).parent().parent().submit();
  });

  $('.b-blogSingle').find('.title,.entry,.post-blog-images,.b-blogMeta').live('mouseover', function(){
    $('.b-blogSingle').has(this).find('.post-edit').show();
  }).live('mouseout', function(){
    $('.b-blogSingle').has(this).find('.post-edit').hide();
  });

  $('.commentItem').live('mouseover', function(){
    $(this).find('.comment-delete').show();
  }).live('mouseout', function(){
    $(this).find('.comment-delete').hide();
  });

  $('.commentItem .comment-delete').live('click', function(){
    var comment = $(".commentItem").has(this);
    $.ajax({
      url: this.href,
      dataType: 'json',
      success: function(data){
        if (data.status == 'error') {
          alert(data.description);
          return;
        }
        comment.remove();
      }
    });
    return false;
  });

  $('.b-filterNav .level1').each(function(){
    if ( $(this).children('ul').size() == 0 ){
      $(this).addClass('empty');
    }
  });

  $('.b-filterNav .level1').hover(function(){
    $(this).addClass('level1-hover').children('.level2-wrapper').show();
  }, function(){
    $(this).removeClass('level1-hover').children('.level2-wrapper').hide();
  });

  $('.subNavItem').hover(function(){
    $(this).addClass('subNavItem-hover').children('.submenu-dropdown').show();
  }, function(){
    $(this).removeClass('subNavItem-hover').children('.submenu-dropdown').hide();
  });

});

/**
 * 
 * Post a compliment to a blog post
 * 
 */
function post_compliment(url, blog_post_id, cplmnt_id)
{
  $("#status_for_"+blog_post_id).append('<div class="ui-pages-loading">&nbsp;</div>');
  
  $.ajax({
    type: "POST",
    cache: false,
    dataTypeString: 'json',
    url: url,
    data: "blog_post_id="+blog_post_id+"&cplmnt_id="+cplmnt_id,
    success: function(data) {
      if(data == "EXIST") {
        $("#status_for_"+blog_post_id).html("You already complimented it!");
      }else{
        $("#compliment_list_for_"+blog_post_id).html(data);
      }
      $(".ui-pages-loading").remove();
      if (typeof $.fn.updateTopStat == 'function') { $.fn.updateTopStat(); }
    },
    error: function() {
      $("#status_for_"+blog_post_id).html("Something wrong, please try again!");
      $(".ui-pages-loading").remove();
    }
  });
}


/**
 * LOADER SCREEN
 */
var loaderBar = new function(){

    this.open = function() {
      $("body").append("<div id='loaderBar'><!-- --></div>");
    };

    this.close = function() {
      $("#loaderBar").remove();
    };

}

/**
 * Welcome Bubble
 */
var welcomeBubble = new function(){

  this.elGlobal = '';
  this.elText   = '';

  this.show = function(el, code, elWidth, elClass) {

    if ( this.elGlobal && this.elGlobal != $(el) ) {
      welcomeBubble.stopTimer();
      $("#wlcBubble").remove();
    }

    if ( !$('#wlcBubble').size() ) {

      $("body").append("<div id='wlcBubble'><div class='text'></div><div class='decor'><!-- --></div><a href='javascript:welcomeBubble.close(\""+code+"\");' class='close'>x</div></div>");

      if ( elWidth && elWidth != '0' ) {
        $("#wlcBubble").width(elWidth);
      }

      if ( elClass ) {
        $("#wlcBubble").addClass(elClass);
      }

      this.elGlobal = $(el);

      this.el       = $(el);
      this.elText   = this.el.attr('title');

      this.elTextExchange = this.el.attr('title').split("|");
      this.elTextJoined = this.elTextExchange.join("</p><p>");

      this.el.attr('title','');

      this.elLeft   = this.el.offset().left;
      this.elTop    = this.el.offset().top;
      this.elH      = this.el.height();
      this.elW      = this.el.outerWidth() / 2;

      this.bubble   = $('#wlcBubble');
      this.bubble.find('.text').html("<p>" + this.elTextJoined + "</p>");
      this.bubbleH  = this.bubble.outerHeight();
      this.bubbleW  = this.bubble.width() / 2;

      this.bubble.css({ left: this.elLeft + this.elW - this.bubbleW });

      if ( this.elTop - this.bubbleH > 0 ) {
        this.bubble.css({ top: this.elTop - this.bubbleH });
      } else {
        this.bubble.addClass('wlcBubbleBottom').css({ top: this.elTop + this.elH });
      };

      this.bubble.hover(function(){
        welcomeBubble.stopTimer();
      }, function(){
        welcomeBubble.hide();
      });

    } else {
      welcomeBubble.stopTimer();
    }

  };// Show end

  this.hide = function() {
    t = setTimeout('$("#wlcBubble").remove();',100);
    this.elGlobal.attr('title',this.elText);
  };

  this.close = function(code) {
    this.elGlobal.attr('title',this.elText);
    var el = this.elGlobal;
    this.hide();
    $.ajax({
      url: window.location.protocol+"//"+window.location.host+"/profile/bubbleSeen",
      data: {'code': code},
      success: function(){
        el.attr('title', null);
        el.attr('onmouseover', null);
        el.attr('onmouseout', null);
      }
    });  
  };


  this.stopTimer = function() {
    clearTimeout(t);
  };

}
