var moduleNames = {
  'mod_relations': 'RelationsModule',
  'mod_recent_media': 'ImagesModule',
  'mod_my_groups': 'MyGroupsModule',
  // '': 'UserInformationModule',
  'community_blog': 'ShowContentModule',
  'mod_photo': 'UserPhotoModule',
  'mod_added_as_a_friend_by': 'InRelationModule',
  'mod_message': 'UserMessagesModule',
  'mod_my_recent_comments': 'RecentCommentsModule',
  'mod_flickr': 'FlickrModule',
  'mod_links_management': 'LinkModule',
  'mod_my_links': 'MyLinksModule',
  'mod_my_network': 'MyNetworksModule',
  'mod_about_user': 'AboutUserModule'
  };

var serialize = function() {
  var ser = {};
  var removed_mod ;//added for opensocial module
  ser['collapsed'] = [];
 // ser['closed'] = [];
  $('div[@id^="col_"]').each( // any div who's id starts with 'col_'
    function() {
      var col = $(this).attr('id');
      var id;
      switch (col) {
        case 'col_a':
          id = 'left';
          break;
        case 'col_b': // this should actually not happen
          id = 'middle';
          break;
        case 'col_c':
          id = 'right';
          break;
        default:
          id = col;
          break;
      }
      ser[id] = [];
      $('.it_module_container', this).each(
        function() {
          var hid;
          try {
            hid = $(this).attr('id');
          } catch(e) {
            return;
          }
          var mid = (moduleNames[hid]) ? moduleNames[hid] : hid;
          if (mid) {//alert(mid)
            if(!$(this).is(':hidden') ) {//alert(mid)
              ser[id].push(mid);
              if( $('div.it_item_content', this).css('display') == 'none') {
                ser['collapsed'].push(mid);
              }
            }
            else {
              removed_mod = mid
            }
          }
        }
      );
    }
  );
  if(!ser['left'].length) {$('#col_a').css('height',100);}
   else {$('#col_a').css('height','auto');}
  if(!ser['middle'].length) {$('#col_b').css('height',100);}
   else {$('#col_b').css('height','auto');}
  if(ser['right']) { if(!ser['right'].length) {$('#col_c').css('height',100);}
   else {$('#col_c').css('height','auto');} }
   $.get(
     base_url+"/ajax/modulesettings.php",
     {
       'page_id': page_id,
       'data': toJSON(ser),
       'removed_mod' : removed_mod,
       'uid': uid

     },
     function(xml) {
        //alert(xml);
     }
   );
}

var do_refresh = function() {
  $('div.it_auto_refresh').each(
    function() {
      inner_mid = $(this).attr('id');
      arr_args = inner_mid.split('_', 2);
      mid = arr_args[1];

      $.get("ajax/refresh_feed.php",{'module_name':mid},
        function(html) {
          if(html) {
            arr_result = html.split('|+|+|', 2);
             $('#inner_'+arr_result[0]).html(arr_result[1]);
//            alert(html);
          }
        }
      );
    }
  );
}

var save_edit_settings = function () {
  module_name = this.elements['module_name'].value; 
  $("#"+module_name+" > div.it_item_content").html("<div class='it_normal_list_block'><del class='no-comments'><img src= '"+skin_url+"/images/loadingAnimation.gif'></del></div>");
    var params = {}; 
    for(i=0; i < this.elements.length; i++) {
      if(this.elements[i].type == 'checkbox' || this.elements[i].type == 'radio') {
        if(this.elements[i].checked) {
          params[ this.elements[i].name ] = this.elements[i].value;
        }
      }
      else {
        params[ this.elements[i].name ] = this.elements[i].value;
      }
    } 
    $.post(
      base_url+"/ajax/save_private_page_setting.php?&random=1",
      params,
      function(htmlData) {
        if(htmlData.search(/>Your session has been expired.</i) == -1) {
          $("#"+module_name+" > div.it_item_content").html(htmlData);
          $("#"+module_name).find("form[@name='item_setting']").bind('submit', save_edit_settings);
          tb_init('a.thickbox, td.thickbox');
        }
        else {
          url = window.location.pathname + window.location.search;
          window.location = base_url + "/login.php?error=1&return=" + encodeURIComponent(url);
        }

      }
    );
    return false;
  }

// this code will be executed as soon as the the page's DOM is ready
$(document).ready(
  function() {

    $(document.body).find("form[@name='item_setting']").bind('submit', save_edit_settings);

    do_refresh_timer = setInterval(do_refresh,60000);
    // collapse/expand click events

    $('.module_block_small_nav > img').click(
      function() {
      var m = this.id;  // getting the parent ID
      var property = this.id.split('_')
      var parnet_obj = $(this).parent().parent().parent().parent().parent();
      var parnet_id = $(parnet_obj).attr('id');
      switch(property[1]) {
        case 'set':
          if ($('div.it_item_content',parnet_obj).is(':hidden')) {
            var minimize_id = property[0] + '_min_' + parnet_id;
            $('#'+minimize_id).attr('src', skin_url+"/images/minimize_module.gif");
            $('#'+minimize_id).attr('title', "Minimize");
            $('div.it_item_content', parnet_obj).slideDown(300,serialize);
          }
          if ($('#control_panel_'+parnet_id).is(':hidden') ) { 
            $('div.it_control_panel', parnet_obj).slideDown(300);
            $('#'+m).attr('title', "Hide Settings");
          }
          else { 
            $('div.it_control_panel', parnet_obj).slideUp(300);
            $('#'+m).attr('title', "Show Settings");
          }
        break;
        case 'min':
          if ($('div.it_item_content',parnet_obj).is(':hidden')) { 
            $('#'+m).attr('src', skin_url+"/images/minimize_module.gif");
            $('#'+m).attr('title', "Minimize");
            $('div.it_item_content', parnet_obj).slideDown(300, serialize);
          }
          else {
            $('#'+m).attr('src', skin_url+"/images/collapse.gif");
            $('#'+m).attr('title', "Restore");
            $('div.it_item_content', parnet_obj).slideUp(300, serialize);
          }
        break;
        case 'close':  
          //show_delete_from_my_page(parnet_id);
        break;
      }
    }
    );
    // init sortable modules
    try {
    $('div[@id^="col_"]').Sortable(
        {
          accept: 'it_module_container',
          helperclass: 'helper-class',
          activeclass : 'sortableactive',
          hoverclass : 'sortablehover',
          handle: 'div.it_module_block_heading',
          tolerance: 'pointer',
          onStop: function() {
            serialize();
        }
      }
    );
    }
    catch (e) {
    }

/*    $('#add_content').click(
      function() {
        $('#CustomizeUIModule').toggle('slow');
      }
    );

    $('#CustomizeUIModule').toggle();*/
    // see if we need to collapse any modules
    if (collapsed) {
      var l = collapsed.length;
      for (var i = 0; i<l; i++) {
        m = collapsed[i];
        try {
        $('#image_min_'+m).attr('src', skin_url+"/images/collapse.gif");
        $('#image_min_'+m).attr('title', "Restore");
        $('#'+m+'/div.it_item_content').toggle();
        }
        catch (e) {
        }
      }
    }
  }
);