// Utility function to check for login status before an action
$(document).ready(function(){
    $("a.checkLoginFirst").bind("click", function(e){
        var strLink = this.href;
        check_login(function() {
        if (strLink) {
                window.location = strLink;
            }
        });
        return false;
    });
});

// PRODUCT AUTOCOMPLETE
$(document).ready(function(){
  var dataurl = SITE_URL + 'ajax/products/getProductList';

  $("input.productAutoCompleteInput").autocomplete(dataurl, {
    multiple: false,
    parse: function(data) {
    return $.map(eval(data), function(row) {
      return {
                data:   row,
                value:  row.group,
                result: row.product
      }
    });
  },
    formatItem: function(item) {
      return acformatItem(item);
    }
  }).result(function(e, item) {
      // item.id; item.product; item.group;
      if($("input#product_id").length) {
        $("input#product_id").val(item.id);
        // Get most recent product price for "Add to Portfolio"
        if (getProductPrice) {
          getProductPrice(item.id, 'inception', '');
          // Update the "since_inception_btn" click handler
          if ($('form$create_order_form input#since_inception_btn').size() > 0) {
            $('form$create_order_form input#since_inception_btn').unbind('click')
                .click(function(){
                  getProductPrice(item.id, 'inception', '');
                });
          }
        }
      }
  });

  $("input.groupAutoCompleteInput").autocomplete(dataurl, {
    multiple: false,
    parse: function(data) {
    return $.map(eval(data), function(row) {
      return {
                data:   row,
                value:  row.group,
                result: row.group
      }
    });
  },
    formatItem: function(item) {
      return acformatItem(item);
    }
  }).result(function(e, item) {

        var dataURL = SITE_URL + 'ajax/GroupAdmin/getGroupDetails/' + item.gid;

        $.ajax({
            type: 'POST',
            url: dataURL,
            dataType: "json",
            success: function(response) {
               if( response.success == true ) {
                   $("div#groups_control_panel_table table tbody").html(response.payload);

               } else {
                   alert(response.errors);
               }
           },
           error: function(xhr, ajaxOptions, thrownError){
              alert("There was an error. Please try again later.");
           }

        });
  });

  $("input.productAutoCompleteAdmin").autocomplete(dataurl, {
    multiple: false,
    parse: function(data) {
    return $.map(eval(data), function(row) {
      return {
                data:   row,
                value:  row.product,
                result: row.product
      }
    });
  },
    formatItem: function(item) {
      return acformatItem(item);
    }
  }).result(function(e, item) {

        var dataURL = SITE_URL + 'ajax/ProductAdmin/getProductDetails/' + item.id +'/' + item.gid;

        $.ajax({
            type: 'GET',
            url: dataURL,
            dataType: "json",
            success: function(response) {
               if( response.success == true ) {
                   $("div#products_control_panel_table table tbody").html(response.payload);

               } else {
                   alert(response.errors);
               }
           },
           error: function(xhr, ajaxOptions, thrownError){
              alert("There was an error. Please try again later.");
           }

        });
  });

  // Initialize title pop-up blurbs
  if (initTitleBlurb) {
    initTitleBlurb();
  }
});

function acformatItem(item){

  return '<p>'+item.group+'<br><span>'+item.product+'</span></p>';
}

function set_group_status(gid, status) {

    var dataURL = SITE_URL + 'ajax/GroupAdmin/setGroupStatus/' + gid + '/' + status;

    $("tr#tr_id_"+gid).css('background-color','#CCE6FF');

    $.ajax({
        type: 'POST',
        url: dataURL,
        dataType: "json",
        success: function(response) {
           if( response.success == true ) {
               alert(response.message);
               $("tr#tr_id_"+gid).remove();

           } else {
               alert(response.errors);
           }
       },
       error: function(xhr, ajaxOptions, thrownError){
          alert("There was an error. Please try again later.");
       }

    });
}

function set_product_status(pid, status, gid) {

    var dataURL = SITE_URL + 'ajax/ProductAdmin/setProductStatus/' + pid + '/' + status + '/' + gid;

    $("tr#tr_id_"+pid).css('background-color','#CCE6FF');

    $.ajax({
        type: 'GET',
        url: dataURL,
        dataType: "json",
        success: function(response) {
           if( response.success == true ) {
               alert(response.message);
               $("tr#tr_id_"+pid).remove();

           } else {
               alert(response.errors);
           }
       },
       error: function(xhr, ajaxOptions, thrownError){
          alert("There was an error. Please try again later.");
       }

    });
}

// TOOLTIPS
$(document).ready(function(){

  $(".tooltip .close").click(function(){
    $(this).parent().slideUp("medium");
    $.get($(this).parent().attr("action")+"?id="+$(this).parent().attr("label"), function(data){ });
    //alert($(this));
  });

  $(".tooltipExtra.true .hidden").each(function(){
    var totalPad = parseInt($(this).parent().css("padding-left"))+parseInt($(this).parent().css("padding-right")) - parseInt($(this).css("padding-left"))- parseInt($(this).css("padding-right"));
    $(this).prepend('<div class="partline" style="width:'+($(this).width()-$(this).parent().width() - totalPad)+'px;"></div>');
    //$(this).find("div.partline").width($(this).parent().width());

    //alert($(this).find("div.partline").width());
  });

  $(".tooltipExtra.true").click(function(){

    $.get($(this).parent().attr("action")+"?id="+$(this).parent().attr("label"), function(data){ });
    if($(this).hasClass("active")){

      $(this).find(".hidden").hide();
      $(this).removeClass("active");

    }else{

      $(this).find(".hidden").show();
      $(this).addClass("active");
    }


   });

});


// ADDRESS BOOK
$(document).ready(function(){

  $(".majorProvider").click(function()
  {
    //alert($(this).val());//debug
    //$(".emailprovider_div").hide();
    switch ($(this).val())
    {
      case 'hotmail':
          $("#selectedProvider").html(
            '<select name="ms_live_domain">'+
              '<option value="hotmail.com">hotmail.com</option>'+
              '<option value="live.com">live.com</option>'+
              '<option value="msn.com">msn.com</option>'+
            '</select>'
          );
          $("#providerList").hide();
          $("#provider").val($(this).val());
        break;
      case 'others':
        $("#selectedProvider").text("");
        $("#providerList").show();
      break;
      default:
        $("#selectedProvider").text($(this).val()+".com");
        $("#providerList").hide();
        $("#provider").val($(this).val());
      break;
    }
  });

  $("#providerList").change(function()
  {
    $("#provider").val($(this).val());
  });

  $("#enterEmailManuallyButton").click(function()
  {
    $("#enterEmailManually").show();
    $("#login2Services").hide();
  });

  $("#back2EmailServices").click(function()
  {
    $("#login2Services").show();
    $("#enterEmailManually").hide();
  });
});



// JavaScript Document

$(document).ready(function(){

  if($.browser.msie && parseInt($.browser.version)<=6){
    $("div#container-wrap").height($(window).height());

  }else{
    $("body").css("overflow", "auto");
    $("div#container-wrap").css("overflow", "auto");
  }

  $(window).resize(function(){
    if($.browser.msie && parseInt($.browser.version)<=6){
    $("div#container-wrap").height($(window).height());
    }
  });

});




//
$(document).ready(function()
{
  if($.cookie('iasgintroduction') != 'closed') {
    $("#introductionBox").show("slow");
  };

  $("#closeIntroduction").click(function()
  {
    $("#introductionBox").hide("slow");
    $.cookie('iasgintroduction', "closed");
  });

  if($.cookie('editprofilebox') != 'closed') {
    $("#editProfileBox").show("slow");
  }

  $("#closeEditProfile").click(function()
  {
    $("#editProfileBox").hide("slow");
    $.cookie('editprofilebox', "closed");
  });

  if($.cookie('iasgGroupintroduction') != 'closed') {
    $("#iasgGroupintroductionBox").show("slow");
  };

  $("#closeiasgGroupintroductionBox").click(function()
  {
    $("#iasgGroupintroductionBox").hide("slow");
    $.cookie('iasgGroupintroduction', "closed");
  });

  if($.cookie('iasgProductintroduction') != 'closed') {
    $("#iasgProductintroductionBox").show("slow");
  };

  $("#closeiasgProductintroductionBox").click(function()
  {
    $("#iasgProductintroductionBox").hide("slow");
    $.cookie('iasgProductintroduction', "closed");
  });

  if($.cookie('iasgHomeGroupToolTips') != 'closed') {
    $("#iasgHomeGroupToolTipsBox").show("slow");
  };

  $("#closeiasgHomeGroupToolTipsBox").click(function()
  {
    $("#iasgHomeGroupToolTipsBox").hide("slow");
    $.cookie('iasgHomeGroupToolTips', "closed");
  });
});

function openThickboxDelayed(url, delay) {
  self.parent.tb_remove();
  setTimeout('self.parent.tb_show(null, "'+url+'", null);', delay);
}

function openThickboxTitleDelayed(title, url, delay) {
  self.parent.tb_remove();
  setTimeout('self.parent.tb_show("'+title+'", "'+url+'", null);', delay);
}

//TAGS CLOUD
function tagCloudInit(tagcloudContainer) {
  $("#"+tagcloudContainer).tagcloud({type:"sphere",height:215,sizemin:8});
}

// Replace missing image
function missingImage(object) {
  object.onerror=null;
  object.width="27";
  object.height="16";
  object.src=IMAGE_URL+'missing.gif';
}

//Request Information
function requestInformationModal(type, name) {

  var requestinfo_view = SITE_URL +"iasgmessage/requestInformationModal/"+encodeURIComponent(name)+"?height=350&width=420";

  self.parent.tb_show("Request more information about this "+type, requestinfo_view, null);

}

//See More Group Activity Feed
function getGroupActivityFeeds(group_id, limit, page, activity_list_id, link_id) {

  //Check if the loading element exist
  var element = $('img#feed_loading').length;
  if(element) $('img#feed_loading').show();

  $.ajax({
    type: "POST",
    url: SITE_URL + 'ajax/activityfeed/getActivityFeed',
    data: {'feed':'group', 'group_id':group_id, 'limit':limit, 'page':page},
    dataType: "json",
    success:  function(response){
                if(response.payload.activity.error) {

                  formatted = '<li title="group">No more activity for this group.<div class="clear"></div></li>';
                  $('ul#'+activity_list_id).append(formatted);
                  $('div#'+link_id).remove();

                } else if(response.success && response.payload.activity) {

                  formatted = '';
                  for (i = 0; i < response.payload.activity.length; i++) {
                    formatted += '<li title="group">' +
                      response.payload.activity[i].sentence +
                      '<br/><span class="time">' +
                      response.payload.activity[i].time +
                      '</span><div class="clear"></div></li>';
                  }

                  $('ul#'+activity_list_id).append(formatted);
                  if(element) $('img#feed_loading').hide();
                }

              }
  });

  return page+=1;
}

/*
 * Switching Show/Hide between 2 element
 * @param Element ID, Element ID
 */

function showHideElment(to_show, to_hide) {
  $("#"+to_show).show();
  $("#"+to_hide).hide();
}

/*
 * Switching active/inactive between 2 button
 * @param Element ID, Element ID, class name
 */
function switchActiveClass(to_active, to_inactive, class_name) {
  $("a."+to_active).addClass(class_name);
  $("a."+to_inactive).removeClass(class_name);
}

/*
 * Edit Import Feed
 * @param name (element name)
 * @param  obj_type (element id or class)
 */
function showLoading(name, obj_type) {
  switch(obj_type) {
    case 'div':
        element = '#'+ name;
      break;
    case 'class':
        element = '.'+ name;
      break;
    default:
      return false;
  }

  $(element).append('<img src="'+IMAGE_V2_URL+'indicator.gif" hspace="4" align="absmiddle"/> Please wait...');
}


function setInstructionText(obj, text_on_blur) {
  if ($(obj).val() == '') {
    $(obj).val(text_on_blur);
    $(obj).addClass('midgrey');
  }
}
function removeInstructionText(obj, text_on_blur) {
  if ($(obj).val() == text_on_blur) {
    $(obj).val('');
    $(obj).removeClass('midgrey');
  }
}
/*
 * Edit Import Feed
 * @param feed_id
 */
function editImportFeed(feed_id) {
  // Switching View -> Edit mode
  $('tr#feed_holder_'+feed_id+' *.feed_viewing').hide();
  $('tr#feed_holder_'+feed_id+' *.feed_editing').show();
}

/*
 * Cancel Editing Import Feed
 * @param feed_id
 */
function cancelEditImportFeed(feed_id) {
  // Switching Edit -> View  mode
  $('tr#feed_holder_'+feed_id+' *.feed_editing').hide();
  $('tr#feed_holder_'+feed_id+' *.feed_viewing').show();

  // Restore feed URL to original
  $('input#url_feed_'+feed_id).val($('span#url_feed_view_'+feed_id).text());

  // Restore feed status to original
  $('select#status_feed_'+feed_id).val($('span#status_feed_view_'+feed_id).text());
}

/*
 * Update Import Feed
 * @param feed_id
 * @param feed_type ('blog_user','blog_group')
 */
function saveEditImportFeed(feed_id, feed_type) {

  var feed_url    = $('input#url_feed_'+feed_id).val();
  var feed_status = $('select#status_feed_'+feed_id).val();

  $.ajax({
    type: "POST",
    url: SITE_URL + 'ajax/rss/updateFeed',
    data: {'feed_id':feed_id, 'feed_url':feed_url, 'feed_status':feed_status, 'feed_type':feed_type},
    dataType: "json",
    success: function(response){
      if (response.success == true) {
        // Set feed URL to display
        $('span#url_feed_view_'+feed_id).text($('input#url_feed_'+feed_id).val());

        // Set feed URL to display
        $('span#status_feed_view_'+feed_id).text($('select#status_feed_'+feed_id).val());
      }
      else {
        alert(response.error);
      }

    },
    error: function(xhr, ajaxOptions, thrownError){
      alert("There was an error while communicating with server. Please try again later.");
    }

  });

  // Switching Edit -> View mode
  $('tr#feed_holder_'+feed_id+' *.feed_editing').hide();
  $('tr#feed_holder_'+feed_id+' *.feed_viewing').show();
}

/*
 * Blog Entries - Delete
 * @param article_id
 * @param blog_type (user or group)
 */
function deleteBlog(article_id, blog_type, group_uri) {

    $.ajax({
      type: "GET",
      url: SITE_URL + 'ajax/blog/deleteBlog/' + article_id + '/' + blog_type + '/' + group_uri,
      dataType: "json",
      success: function(response){
          if (response.success == true) {
              alert(response.message);
              $('span#delete_blog_'+article_id).remove();
              $('span#status_blog_'+article_id).text('deleted');
          }
          else {
              alert(response.error);
          }

      },
      error: function(xhr, ajaxOptions, thrownError){
          alert("There was an error while communicating with server. Please try again later.");
      }

   });
}
