if( typeof( api ) == "undefined" ){
   api = {
   }; api.ns = 'api'; };


/**
 * Item model. Represents a single channel item
 */
api.Item = function( item_dictionary ){

  var i;

  var attributes = [
		     'category',
		     'content_type',
		     'description',
		     'id',
		     'time_created',
		     'embed_url_l',
		     'embed_url_s',
		     'embed_target_url',
		     'thumb_url',
    		     'medium_url',
		     'nxcid',
    		     'url',
		     'detail_url',
		     'pcids',
		     'hosted_image'
		   ];

  // Copy all supported attributes
  for( i = 0; i < attributes.length; i++ ){
    this[attributes[i]] = item_dictionary[attributes[i]];
  }

  api.Item.items[item_dictionary['id']] = this;
};

api.Item.items = {};

api.Item.prototype = {

  to_lightbox_img : function(){
    return {
      'src' : this.medium_url,
      'title' : this.description,
      'iid' : this.id,
      'image' : true
    };
  }

};

/**
 * Retrieve the set of hosted items for the specified user.
 * @param psid Pickled (sequence) Item ID
 * @param count Maximum number of items to fetch
 * @param on_fetch Callback for item retrieval, receives {items, psid, total item count}
 */
api.Item.fetch = function(pcid, psid, count, on_fetch) {

  AppBase.post(
    '/items',
    {
      'xaction' : 'get_channel_items',
      'pcid': pcid,
      'psid' : psid,
      'count' : count
    },
    function(response){ api.Item._on_fetch( on_fetch, response ); }
  );
  return false;
};

api.Item._on_fetch = function( callback, result ){
  var items = [];
  for( var i = 0; i < result['items'].length; i++ ){
    items[items.length] = new api.Item( result['items'][i]);
  }
  callback( items, result['psid'], result['items_total'] );
};

/**
 * Retrieve the set of hosted items for the specified user.
 * @param psid Pickled (sequence) Item ID
 * @param count Maximum number of items to fetch
 * @param on_fetch Callback for item retrieval, receives {items, psid, total item count}
 */
api.Item.fetch_hosted = function(psid, count, on_fetch) {

  AppBase.post(
    '/items',
    {
      'xaction' : 'get_hosted_items',
      'psid' : psid,
      'count' : count
    },
    function(response){ api.Item._on_fetch_hosted( on_fetch, response ); }
  );
  return false;
};

api.Item._on_fetch_hosted = function( callback, result ){
  var items = [];
  for( var i = 0; i < result['items'].length; i++ ){
    items[items.length] = new api.Item( result['items'][i]);
  }
  callback( items, result['psid'], result['items_total'] );
};

/**
 * Remove the hosted item.
 * Callback is invoked with {iid, cid, rval}
 * @param iid Item ID
 */
api.Item.remove_hosted = function( iid, on_remove ){
  AppBase.post(
    '/items',
    {
      'xaction' : 'remove_hosted_item',
      'iid' : iid,
      'nxcid' : api.Item.items[iid]['nxcid']
    },
    function(response){ api.Item._on_remove_hosted( on_remove, response ); }
  );
  return false;
}; api.Item._on_remove_hosted = function( callback, response ){ callback( response ); };

/**
 * Remove the item from the channel.
 * Callback is invoked with {iid, cid, rval}
 * @param iid Item ID
 */
api.Item.remove = function( iid, pcid, on_remove ){
  if( pcid == 'hosted' ){
    return api.Item.remove_hosted( iid, on_remove );
  }

  AppBase.post(
    '/items',
    {
      'xaction' : 'remove',
      'iid' : iid,
      'pcid' : pcid
    },
    function(response){ api.Item._on_remove_hosted( on_remove, response ); }
  );
  return false;
}; api.Item._on_remove_hosted = function( callback, response ){ callback( response ); };


/**
 * Create a funpix with the specified item.
 * Callback is invoked with the arrange page for the new funpix.
 * @param iid Item ID
 */
api.Item.create_funpix = function( iid, on_create ){
  AppBase.post(
    '/items',
    {
      'xaction' : 'create_pic_channel_from_item',
      'iid' : iid
    },
    function(response){ api.Item._on_create_funpix( on_create, response ); }
  );
  return false;
}; api.Item._on_create_funpix = function( callback, response ){ callback( response ); };

/**
 * Create a slideshow starting with the specified item.
 * Callback is invoked with the arrange page for the new slideshow.
 * @param iid Item ID
 */
api.Item.create_slideshow = function( iid, on_create ){
  AppBase.post(
    '/items',
    {
      'xaction' : 'create_channel_from_item',
      'iid' : iid
    },
    function(response){ api.Item._on_create_slideshow( on_create, response ); }
  );
  return false;
}; api.Item._on_create_slideshow = function( callback, response ){ callback( response ); };

/**
 * Updates the description of the specified item
 * @param iid Item ID
 * @param description New Description
 */
api.Item.update_description = function( iid, description, on_update ){
  AppBase.post(
    '/items',
    {
      'xaction' : 'update_description',
      'iid' : iid,
      'nxcid' : api.Item.items[iid]['nxcid'],
      'description' : description
    },
    function( response ){api.Item._on_update_description(on_update, response);}
  );
}; api.Item._on_update_description = function( callback, response ){ callback( response ); };

api.Item.Template = function(){
  api.Item.Template.instance = this;
};

api.Item.Template.prototype = {


  render_items : function( items ){
    var toRet = [];
    for( var i = 0; i < items.length; i++ ){
      var headerRow = DIV({'id':items[i]['id']+'_l', 'class':'legend'},this.render_header( items[i]));
      var imgRow = DIV({'id':items[i]['id']+'_p','class':'picture'},this.render_image( items[i] ));
      var embedRow = this.render_embeds( items[i] );
      var container = DIV({'class':'picture_container',
			   'id':items[i]['id']+'_container'
			  }, headerRow, imgRow, embedRow);
      toRet[ toRet.length ] = container;
    }

    return toRet;
  },

  render_items_compact : function( items, pcid ){
    var toRet = [];
    for( var i = 0; i < items.length; i++ ){
      var myDelete = api.Item.Template._item_options['delete'](items[i], pcid);
      if( pcid == 'hosted' )
	var ctrlRow = DIV({'class':'item_delete'}, A({'href':'#', 'onclick':myDelete.onclick},IMG({'src':myDelete.img})));
      else
	var ctrlRow = DIV({'style':'height:10px'},'&nbsp;');
      var footerRow = DIV({'id':items[i]['id']+'_l', 'class':'legend'},this.render_footer( items[i]));
      var imgRow = DIV({'id':items[i]['id']+'_p','class':'picture'},this.render_image( items[i] ));
      var container = DIV({'class':'picture_container',
			   'id':items[i]['id']+'_container'
			  }, ctrlRow, imgRow, footerRow);
      toRet[ toRet.length ] = container;
    }

    return toRet;
  },

  post_render : function( items ){
    /**
    for( var i = 0; i < items.length; i++ ){
      $('#img_'+items[i]['id']).load( function(){alert("foo");} );
    }*/
  },


  render_image : function( item ){
    var img = "<img onload='api.Item.Template.center_item(\""+item['id']+"\")' src='"+item['thumb_url']+"' alt='"+item['description']+"'/>";
    var a = A({'href':item['detail_url'],
	      'src':item['medium_url'],
	      'title':item['description'],
	      'iid':item['id'],
	      'hosted_image':item['hosted_image'],
	      'url':item['url'],
	      'id':'href_'+item['id']}
	    );
    a.innerHTML = img;
    return a;

  },

  render_header : function( item ){
    return DIV({'class':'item_header'},
                 this.render_description_edit(item),
		 this.render_options( item )
	       );
  },

  render_footer : function( item ){
    return DIV({'class':'item_header'},
                 this.render_description_edit(item)
	       );
  },

  render_description_edit : function( item ){
    return DIV({},
	       DIV({'id':'fk_'+item['id'],
		    'onclick':'api.Item.Template.desc_edit_show("'+item['id']+'")',
		    'class' : 'caption_fake'
		   },
		   DIV({'class':'icon'},
		       IMG({'src':Serdes.make_static_url('/images/slidecom/actions/edit.gif'), 'alt':'edit'})
		       ),
		   DIV({'class':'description'},item["description"])
	       ),
	       DIV({'id':'re_'+item['id'], 'class' : 'caption_real'},
		   $("<form onsubmit='return api.Item.Template.desc_submit(\""+item['id']+"\")'><INPUT type='text' class='description' value='"+item['description']+"'/><INPUT class='submit_button' value='ok' type='submit' onclick='return api.Item.Template.desc_submit(\""+item['id']+"\")'/></form>")[0],
		   A({'onclick':'return api.Item.Template.desc_cancel("'+item['id']+'")','href':'#'},'cancel')
		  ),
	       DIV({'id':'ld_'+item['id'], 'class':'caption_load'},
		   IMG({'src':Serdes.make_static_url('/images/fbjq_dialog_loading.gif')}))
	      );
  },

  render_uploader : function( ){
    return INPUT({'id':'progress_bar_binary',
		  'type':'file',
		  'onchange':'api.Item.Template.doUploadProgressBar(this, null,"",null);',
		  'size':'16',
		  'onkeydown':'return false;'});
  },

  render_embeds : function(item){
    var dropDown = DIV({'class':'select'});
    dropDown.innerHTML = '<select name="embed" onchange="api.Item.Template.embed_select(\''+item['id']+'\', this.value)"><option selected value="sw">'+translate('small_web')+'</option><option value="lw">'+translate('large_web')+'</option><option value="sf">'+translate('small_forum')+'</option><option value="lf">'+translate('large_forum')+'</option></select>';
    return DIV({'class':'embeds'},
	      DIV({},translate('embed_codes')),
	      INPUT({'type':'text',
		     'readonly':'readonly',
	             'id':'embed_'+item['id'],
		     'value' : api.Item.Template.str_embed_code(item['id'],'s','w'),
		     'onclick' : function(){ this.focus(); this.select();}
		    }),
	       dropDown
	       );
  },

  render_options : function( item ){
    var menu_options_hashes = [];
    var menu_options = [];

    api.Item.Template.add_item_option( menu_options_hashes, item, 'show_original' );
    api.Item.Template.add_item_option( menu_options_hashes, item, 'delete' );

    var parental = DIV({ 'class':'item_menus', 'class':'options' });
    if (menu_options_hashes.length) {
      var item_options_menu_wrapper = DIV({'class':'item_options_menu_wrapper', 'style':'float:right'});
      menu_options.push(item_options_menu_wrapper);
      AppBase.create_menu(item_options_menu_wrapper, 'options_'+item['id'], 'item_options', menu_options_hashes);
    }

    jQuery.each(menu_options, function( which_menu, each_menu ){
      $(parental).append(each_menu);
    });
    return parental;
  }
};

// Static actions for Template
api.Item.Template._on_item_delete = function(iid){
  $('#'+iid+'_container').fadeOut();
  $('#'+iid+'_container').remove();
  $.Lightbox.total_image_count -= 1;
  api.Item.Template.on_item_delete( iid );
};

api.Item.Template.forward_url = function(url){
  window.location = url;
};

api.Item.Template.add_item_option = function(menu_list, item, option){
    opt = api.Item.Template._item_options[option](item);
    menu_list.push( opt );
};

api.Item.Template._item_options = {
    'show_original': function(item) {
	return {'name':'show_original',
		'href':item['url'],
		'onclick':'return true',
		'img':Serdes.make_static_url('/images/slidecom/actions/download.gif')
	       };
    },
    'delete': function(item, pcid) {
	return {'name':'delete',
		'href':'#',
		'onclick' : function(){ if (window.confirm(translate('Are_you_sure_owner'))) {
		    api.Item.remove( item['id'], pcid, function(){api.Item.Template._on_item_delete(item['id']);});
		  }},
		'img':Serdes.make_static_url('/images/slidecom/actions/delete.gif')
	       };
    }
};


/*
 * Hide the DESCRIPTION editor
 */
api.Item.Template.desc_edit_hide = function( iid ){
  $('#re_'+iid).hide(); $('#fk_'+iid).show();
  $('div#'+iid+'_l .item_header .options').show();
};

/**
 * Show the DESCRIPTION editor
 */
api.Item.Template.desc_edit_show = function( iid ){
  $('#re_'+iid).show();
  $('#fk_'+iid).hide();
  $('div#'+iid+'_l .item_header .options').hide();
  $('#re_'+iid+' input')[0].focus();
  $('#re_'+iid+' input')[0].select();
};

/**
 * Submit the DESCRIPTION change
 */
api.Item.Template.desc_submit = function( iid ){
  var val = $('#re_'+iid+' input')[0].value;
  $('#fk_'+iid+' div.description')[0].innerHTML = val;
  api.Item.items[iid]['description'] = val;
  $('#href_'+iid).attr('title',val);
  $('#re_'+iid).hide();
  $('#ld_'+iid).show();
  api.Item.update_description( iid, val, api.Item.Template.on_desc_submit );
  return false;
};

/**
 * Cancel the DESCRIPTION change
 */
api.Item.Template.desc_cancel = function( iid ){
  $('#re_'+iid+' input')[0].value = api.Item.items[iid]['description'];
  api.Item.Template.desc_edit_hide(iid);
  return false;
};


api.Item.Template.on_desc_submit = function( response ){
  $('#ld_'+response['iid']).hide();
  api.Item.Template.desc_edit_hide( response['iid'] );
  api.Item.Template.on_description_change( response['iid']);
};

api.Item.Template.center_item = function( iid ){
  var containerH = $('#'+iid+'_container div.picture').height();
  var picH = $('#'+iid+'_container div.picture img').height();
  var offset = Math.ceil((containerH - picH) / 2) - 4;
  var imgs = $('#'+iid+'_container div.picture img');
  if( imgs.length > 0 ){
    imgs[0].style.marginTop = offset+"px";
    $('#'+iid+'_container').css('display','none');
    $('#'+iid+'_container').css('visibility', 'visible');
    $('#'+iid+'_container').fadeIn();
  }

};

api.Item.Template.embed_select = function( item_id, select_val ){
  $("#embed_"+item_id)[0].value = api.Item.Template.str_embed_code( item_id, select_val.substr(0,1), select_val.substr(1,1));
};

/**
 * Returns the embed code for the specified size and target
 * @param item_id Item ID as a string
 * @param size s or l for Small or Large
 * @param target f or w for Forum or Web
 * @return String embed code
 */
api.Item.Template.str_embed_code = function( item_id, size, target ){
    var desc = api.Item.items[item_id]['description'];
    var src_img = api.Item.items[item_id]['embed_url_'+size];
    var t_url = api.Item.items[item_id]['embed_target_url'];
    if( target == 'w' ){
      return "<a target='_blank' href='"+t_url+"'><img src='"+src_img+"' border='0' alt='"+desc+"' title='"+desc+"' /></a>";
    }else if( target == 'f' ){
      return "[URL="+t_url+"][IMG]"+src_img+"[/IMG][/URL]";
    }
    return "";
};

/**
 * CALLBACK -- invoked when an item's description has changed
 */
api.Item.Template.on_description_change = function( iid ){};

api.Item.Template.on_item_delete = function( iid ){};


