function ItemManager()
{
    var self        = this,
        linksToDisplay ,
        lastItem = 0,
        allItemArr = [],
        type,
        intervalInSeconds,
        key,
        interval,
        itemArr = [],
        containerEl,
        onItemRatedGlobalFunction,
        onItemPublishedGlobalFunction,
        onItemDeletedGlobalFunction,
        headerAndFooterHeight;
        
    this.renderStartEvent = new YAHOO.util.CustomEvent("renderStartEvent", this);
    this.renderFinishEvent = new YAHOO.util.CustomEvent("renderFinishEvent", this);
        
    this.init = function(cfg)
    {
        self.renderStartEvent.fire();
        
        containerEl = YUD.get(cfg.containerElId);        
        containerEl.innerHTML = "";
        
        headerAndFooterHeight = cfg.headerAndFooterHeight;
        self.updateListHeight();
        YUE.addListener(window, "resize", self.updateListHeight)
        
        onItemRatedGlobalFunction = cfg.onItemRatedGlobalFunction;
        onItemPublishedGlobalFunction = cfg.onItemPublishedGlobalFunction;
        onItemDeletedGlobalFunction = cfg.onItemDeletedGlobalFunction;

        linksToDisplay = cfg.linksToDisplay;
        type = cfg.type;
        intervalInSeconds = cfg.intervalInSeconds;

        key = "LAST_ITEM_"+type;
    
        if (cfg.initialItems !== null)
        {
            self.addItems(cfg.initialItems,linksToDisplay);
            allItemArr = cfg.initialItems;
        }

        self.renderFinishEvent.fire();
    }
    
     this.addItem = function(cfgString, withAnimation)
    {
        var item = new Item();
        item.onRate.subscribe(onItemRated);
        item.onPublish.subscribe(onItemPublished);
        item.onDelete.subscribe(onItemDeleted);

        if(cfgString != "")
        {
            var cfgJSON = YAHOO.lang.JSON.parse(cfgString);
            var itemEl = item.init(cfgJSON);
            insertIntoDom(itemEl, withAnimation)
            itemArr.push(item);
            
            lastItem = lastItem + 1;
           
            //cookie
             var current_date = new Date;
             var cookie_year = current_date.getFullYear ( ) + 1;
             var cookie_month = current_date.getMonth ( );
             var cookie_day = current_date.getDate ( );
             set_cookie ( key, cfgJSON.publishDate, cookie_year, cookie_month, cookie_day );
             
             hideLinkNoNews();
        }
    }
    
    this.addItems = function(itemCfgArr,linksToDisplay)
    {
        var withAnimation = false;
        
        if(itemCfgArr.length < linksToDisplay)
        {
          linksToDisplay = itemCfgArr.length;
        }
        
        for (var i = 0; i<linksToDisplay; i++)
        {
            self.addItem(itemCfgArr[i], withAnimation);
        }
        
        if(itemCfgArr.length == 0){
             showLinkNoNews();
        }
        else{
             hideLinkNoNews();
        }
        
        setNewsInterval();

    }

 
 
    this.showNext = function()
    {
          if(lastItem<allItemArr.length)
          {
               var item = allItemArr[lastItem];
               self.addItem(item,true);
          }
          else
          {
               var json = GBNews.BusinessObjectLayer.AjaxMethod.GetNextNewsJSon(type, get_cookie(key));  
               if(json.value != null)
               {
                   lastItem = 0;
                   allItemArr = json.value;
                   
                   if(itemArr.length == 0)
                   {
                     clearNewsInterval();
                     self.addItems(json.value,linksToDisplay);
                   }
                   else if(allItemArr.length > 0)
                   {
                       var item = allItemArr[lastItem];
                       self.addItem(item,true);
                   }
               }  
          }
    }
    
    this.getIntervalInSeconds = function(){
      return intervalInSeconds;
    }
    
    this.updateItemRating = function(itemId, ratingString)
    {
        var item = getItemById(itemId);
        if (item !== null)
        {
            var ratingJSON = YAHOO.lang.JSON.parse(ratingString);
            item.updateRating(ratingJSON);
        }
    }
    
    this.updateListHeight = function(type, args, scope)
    {
        var viewportHeight = YUD.getViewportHeight();
        if (typeof args !== "undefined"){
            var offset = args[0];
            headerAndFooterHeight = headerAndFooterHeight + offset;
        }
        YUD.setStyle(containerEl.parentNode, "height", viewportHeight - headerAndFooterHeight + "px");
    }
    
    var insertIntoDom = function(itemEl, withAnimation)
    {        
        if (itemArr.length == 0)
        {
            containerEl.appendChild(itemEl);
        }
        else
        {
            var endPosition = YUD.getXY(containerEl);
            var lastItemEl = itemArr[itemArr.length-1].getElement()
            containerEl.insertBefore(itemEl, lastItemEl);
            var itemHeight = itemEl.offsetHeight + parseInt(YUD.getStyle(itemEl, "margin-bottom"), 10);

            if (withAnimation)
            {
                YUD.setStyle(containerEl, "top", itemHeight*-1 + "px");
                var animation = new YAHOO.util.Motion(containerEl, {points: { to: endPosition }}, 0.4, YAHOO.util.Easing.easeBoth);
                animation.animate();
            }
        }
    }
    
    var onItemRated = function(type, args, scope)
    {
        var cfg = args[0];
        onItemRatedGlobalFunction.call(null, cfg);
    }
    
    var onItemPublished = function(type, args, scope)
    {
        var cfg = args[0];
        onItemPublishedGlobalFunction.call(null, cfg);
    }
    
    var onItemDeleted = function(type, args, scope)
    {
        var cfg = args[0];        
        onItemDeletedGlobalFunction.call(null, cfg);
        removeFromItemArr(cfg.itemId);
    }
    
    var getItemById = function(itemId)
    {
        for (var i = 0; i<itemArr.length; i++)
        {
            if (itemArr[i].getId() === itemId)
            {
                return itemArr[i];
            }
        }
        return null;
    }
    
    var getItemIndexById = function(itemId)
    {
        for (var i = 0; i<itemArr.length; i++)
        {
            if (itemArr[i].getId() === itemId)
            {
                return i;
            }
        }
        return null;
    }
    
    var removeFromItemArr = function(itemId){
        var itemIndex = getItemIndexById(itemId);
        if (itemIndex){
            itemArr.splice(itemIndex, 1);
        }
    }
}
function Item()
{
    var self = this,
        cfg,
        itemEl,
        rateEl,
        rateDisplayEl,
        itemContentEl,
        toggleStatusEl,
        published;
        
    this.onRate = new YAHOO.util.CustomEvent("onRate", this);
    this.onPublish = new YAHOO.util.CustomEvent("onPublish", this);
    this.onDelete = new YAHOO.util.CustomEvent("onDelete", this);
    
    this.init = function(_cfg)
    {
    //debugger
        /*
            '{
                "id": "000-asdsas0-0",
                "feed":
                {
                    "title": "Michael Jordan returns to the Chicago Bulls",
                    "url": "http://www.ynet.co.il/article/2343324",
                    "date": "22/01/09",
                    "referer":
                    {
                        "name": "YNET",
                        "url": "http://www.ynet.co.il",
                        "imageURL": "path/logo_ynet.gif"
                    }
                },
                "rating":
                {
                    "alreadyRatedByUser": true,
                    "good": 43,
                    "bad": 15
                }            
            }'
        */
        
        /*
            <li class="item">
                 <div class="item_info">
                    <span class="date">
                        22/01/09
                    </span>
                    <a href="http://www.ynet.co.il" target="_blank">
                        (YNET)
                    </a>
                    <div class="rating_graph">
                        <span></span>
                    </div>
                 </div>
                 <div class="item_content">
                    <span class="lnk_rate lnk_rate_good">
                        <a href="javascript://">+</a>
                    </span>
                    <span class="title">
                        <a href="http://www.ynet.co.il/article/2343324" target="_blank">
                            Michael Jordan returns to the Chicago Bulls
                        </a>
                    </span>                    
                    <span class="lnk_rate lnk_rate_bad">
                        <a href="javascript://">-</a>
                    </span>
                 </div>                 
            </li>
        */
        
        cfg = _cfg;
        _cfg = null;
        
        itemEl = document.createElement("LI");
        YUD.addClass(itemEl, "item");
        YUE.addListener(itemEl, "mouseover", onmouseover);
        YUE.addListener(itemEl, "mouseout", onmouseout);
        
        rateEl = document.createElement("DIV");
        YUD.addClass(rateEl, "item_rating");
        YUD.addClass(rateEl, "clearfix");
        itemEl.appendChild(rateEl);
        
        var rateGoodEl = document.createElement("SPAN");        
        YUD.addClass(rateGoodEl, "lnk_rate");        
        YUD.addClass(rateGoodEl, "lnk_rate_good");
        if (cfg.rating){
            var rateGoodLinkEl = document.createElement("A"); 
            rateGoodLinkEl.setAttribute("href", "javascript://");
            YUE.addListener(rateGoodLinkEl, "click", rateGood, true);
            if (YAHOO.env.ua.ie > 0)
            {
                YUE.addListener(rateGoodLinkEl, "focus", hideLinkOutline);
            }
            rateGoodEl.appendChild(rateGoodLinkEl);
        }
        rateEl.appendChild(rateGoodEl);        
        
        var rateBadEl = document.createElement("SPAN");       
        YUD.addClass(rateBadEl, "lnk_rate");       
        YUD.addClass(rateBadEl, "lnk_rate_bad");
        if (cfg.rating){
            var rateBadLinkEl = document.createElement("A");  
            rateBadLinkEl.setAttribute("href", "javascript://");
            YUE.addListener(rateBadLinkEl, "click", rateGood, false);
            if (YAHOO.env.ua.ie > 0)
            {
                YUE.addListener(rateBadLinkEl, "focus", hideLinkOutline);
            }        
            rateBadEl.appendChild(rateBadLinkEl);
        }
        rateEl.appendChild(rateBadEl);
        
        if (cfg.rating){
            rateDisplayEl = document.createElement("DIV");        
            YUD.addClass(rateDisplayEl, "rating_graph");
            var goodEl = document.createElement("SPAN");
            rateDisplayEl.appendChild(goodEl);
            rateEl.appendChild(rateDisplayEl);
            updateRatingEl();
        }
        
        itemContentEl = document.createElement("DIV");     
        YUD.addClass(itemContentEl, "item_content");
        YUD.addClass(itemContentEl, "clearfix");
        itemEl.appendChild(itemContentEl);
        
        var timeEl = document.createElement("DIV");        
        YUD.addClass(timeEl, "item_time");     
        itemContentEl.appendChild(timeEl);
        
        var dateEl = document.createElement("SPAN");        
        YUD.addClass(dateEl, "date");        
        var date = document.createTextNode(cfg.feed.date);
        dateEl.appendChild(date);
        timeEl.appendChild(dateEl);
        
        var hourEl = document.createElement("SPAN");        
        YUD.addClass(hourEl, "hour");        
        var hour = document.createTextNode(cfg.feed.hour);
        hourEl.appendChild(hour);
        timeEl.appendChild(hourEl);
            
        var titleEl = document.createElement("SPAN");
        YUD.addClass(titleEl, "title");
        var titleLinkEl = document.createElement("A"); 
        var title = document.createTextNode(cfg.feed.title);
        titleLinkEl.appendChild(title);
        titleLinkEl.setAttribute("href", cfg.feed.url);
        titleLinkEl.setAttribute("target", "_blank");
        titleEl.appendChild(titleLinkEl);
        itemContentEl.appendChild(titleEl);
        
        if (cfg.feed.referer.imageURL){            
            var refererEl = document.createElement("A");        
            YUD.addClass(refererEl, "referer");
            refererEl.setAttribute("href", cfg.feed.referer.url);
            refererEl.setAttribute("target", "_blank");           
            YUD.setStyle(refererEl, "background-image", "url("+cfg.feed.referer.imageURL+")");
            refererEl.innerHTML = cfg.feed.referer.name;
            titleEl.appendChild(refererEl);        
        }
        
        //YUD.addClass(rateEl, "show_rating_graph");
        if (cfg.rating && cfg.rating.alreadyRatedByUser)
        {
           switchRatingView();
        }
        
        if (cfg.AdminInfo)
        {
            var adminEl = document.createElement("DIV");     
            YUD.addClass(adminEl, "admin");            
            itemEl.appendChild(adminEl);
            
            toggleStatusEl = document.createElement("A");
            var text;
            if (cfg.AdminInfo.status === "Published")
            {
                text = "UnPublish";
                published = true;
            }
            else
            {
               text = "Publish"; 
               published = false;
            }
            text = document.createTextNode(text);
            toggleStatusEl.appendChild(text);
            YUD.addClass(toggleStatusEl, "lnk_publish");
            toggleStatusEl.setAttribute("href", "javascript://");
            YUE.addListener(toggleStatusEl, "click", publish);
            adminEl.appendChild(toggleStatusEl);
            
            var breaklineEL = document.createElement("BR");
            adminEl.appendChild(breaklineEL);
            
            var deleteEl = document.createElement("A");
            text = document.createTextNode("Delete");
            deleteEl.appendChild(text);
            YUD.addClass(deleteEl, "lnk_delete");
            deleteEl.setAttribute("href", "javascript://");
            YUE.addListener(deleteEl, "click", deleteItem);
            adminEl.appendChild(deleteEl);
        }
        
        return itemEl;
    }
    
    this.updateRating = function(newRating)
    {
        cfg.rating = newRating;
        updateRatingEl();
    }
    
    this.getId = function()
    {
        return cfg.id;
    }
    
    this.getElement = function()
    {
        return itemEl;
    }
    
    var publish = function(){
        self.onPublish.fire(
            {
                "itemId": cfg.id,
                "publish": !published
            }                
        );
        togglePublishLinkText();
    }
    
    var deleteItem = function(){
        self.onDelete.fire(
            {
                "itemId": cfg.id
            }                
        );
        itemEl.parentNode.removeChild(itemEl);
    }
    
    var rateGood = function(type, args, scope)
    {
        var ratedGood = args; //boolean
        self.onRate.fire(
            {
                itemId: cfg.id,
                ratedGood: ratedGood,
                ratingGood :cfg.rating.good,
                ratingBad :cfg.rating.bad
            }
        );    
        //switchRatingView(ratedGood); 
        animateRating(ratedGood);   
    }
    var hideLinkOutline = function(){
        this.hideFocus=true;
    }
    
    var updateRatingEl = function()
    {
        var goodValue =0;
        if(cfg.rating.good>0 || cfg.rating.bad>0)
         {
        /* calculate new goodEl width*/
            goodValue = cfg.rating.good / (cfg.rating.good + cfg.rating.bad);
         }
        
            goodValue = goodValue * 100;
            goodValue = parseInt(goodValue, 10);
        
        var goodEl = rateDisplayEl.firstChild;
        YUD.setStyle(goodEl, "width", goodValue + "%"); 
        
        goodEl.setAttribute("title", goodValue + "%");
        rateDisplayEl.setAttribute("title", 100 - goodValue + "%");
    }
    
    var switchRatingView = function(){
        YUD.addClass(rateEl, "show_rating_graph");
        YUD.addClass(itemEl, "rated");
        disableRatingLinks();
    }
    
     var animateRating = function(ratedGood){
        if(ratedGood)
        {
            animateRatedGood();
        }
        else
        {
            animateRatedBad();
        }
    }
    
    var animateRatedGood = function(){
       var animAttributes = {
            left: {to: 1000},
            opacity: {to: 0}
        };
       animateRated(animAttributes);
    }
    var animateRatedBad  = function(){
            var animAttributes = {
            left: {to: -1000},
            opacity: {to: 0}
        };
       animateRated(animAttributes);
    }
    var animateRated = function(animAttributes){
         //var itemAnim = new YAHOO.util.Anim(itemEl, animAttributes, 0.8);
         var itemAnim = new YAHOO.util.Anim(itemEl, animAttributes, 0.5, YAHOO.util.Easing.easeIn);
        
        itemAnim.onComplete.subscribe(function(){
            YUD.setStyle(itemEl, "display", "none");
        });
        
        itemAnim.animate();
    }
    
    
    var togglePublishLinkText = function(){
        if (published === true)
        {
            toggleStatusEl.innerHTML = "Publish";
            published = false;
        }
        else
        {
           toggleStatusEl.innerHTML = "UnPublish";
           published = true;
        }
    }
    
    var disableRatingLinks = function()
    {
        YUD.addClass(rateEl, "hide_rate_links");
        var links = itemContentEl.getElementsByTagName("A");
        for (var i = 0; i<links.length; i++)
        {
            YUE.removeListener(links[i], "click");
        }
    }
    
    var onmouseover = function(){
        YUD.addClass(itemEl, "item_hover");
        clearNewsInterval();
    }
    
    var onmouseout = function(){
        YUD.removeClass(itemEl, "item_hover");
        setNewsInterval();
    }
}



// start cookie
function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
  var cookie_string = name + "=" + escape ( value );

  if ( exp_y )
  {
    var expires = new Date ( exp_y, exp_m, exp_d );
    cookie_string += "; expires=" + expires.toGMTString();
  }

  if ( path )
        cookie_string += "; path=" + escape ( path );

  if ( domain )
        cookie_string += "; domain=" + escape ( domain );
  
  if ( secure )
        cookie_string += "; secure";
  
  document.cookie = cookie_string;
}

function get_cookie ( cookie_name )
{
  var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

  if ( results )
    return ( unescape ( results[2] ) );
  else
    return null;
}
//end cookie






var itemManager = new ItemManager();
itemManager.renderStartEvent.subscribe
(
    function()
    {
        var HTMLtag = document.getElementsByTagName("HTML")[0];
        YUD.addClass(HTMLtag, "loading");
    }
);
itemManager.renderFinishEvent.subscribe
(
    function()
    {
        var HTMLtag = document.getElementsByTagName("HTML")[0];
        YUD.removeClass(HTMLtag, "loading");
        YUD.addClass(HTMLtag, "done_loading");
    }
);

var upperMessage = new UpperMessage();
upperMessage.onHideAnimComplete.subscribe
(
    function()
    {
        itemManager.updateListHeight(null, [upperMessage.getElementHeight()*-1]);
    }
);
upperMessage.onShowAnimComplete.subscribe
(
    function()
    {
        itemManager.updateListHeight(null,[upperMessage.getElementHeight()]);
    }
);

function onItemRated(cfg)
{
    if(cfg.ratedGood)
    {
        cfg.ratingGood = cfg.ratingGood+1;
        Rating(cfg.itemId,"Good");
    }
    else
    {
        cfg.ratingBad = cfg.ratingBad+1;
        Rating(cfg.itemId,"Bad");
    }
   
    var ratingString = '{"good": ';
    ratingString += cfg.ratingGood;
    ratingString += ', "bad": ';
    ratingString += cfg.ratingBad;
    ratingString += '}';
    
    
    itemManager.updateItemRating(cfg.itemId, ratingString);
}

//rating
function Rating(id,type)
{
    GBNews.BusinessObjectLayer.AjaxMethod.UpdateRating(id,type,Rating_callback);
}

function Rating_callback(res)
{
    if (res.value !=null)
    {
        var i=0;
    }
}

function AddItemToArray(type)
{
      var value = GBNews.BusinessObjectLayer.AjaxMethod.GetNewItemJSon(type);
      if(json.value != null)
      {
        itemManager.addItem(json.value.Value, true); 
      }                              
}

function GetNewsByHours(type,linksToDisplay)
{
    var json = GBNews.BusinessObjectLayer.AjaxMethod.SetCookieHoursValue(type,'24');   
    
    itemManager.showNext();
    hideLinkNoNews();
}

/*start LinkAllNews */
function showLinkNoNews()
{
   YUD.setStyle('noNews','display','block');
}
function hideLinkNoNews()
{
   moveNoNews();
}
/*end LinkAllNews*/

/*start interval*/
function clearNewsInterval() {
      clearInterval(interval);
}
function setNewsInterval() {
      interval = setInterval ( function(){
                itemManager.showNext();
             }, itemManager.getIntervalInSeconds()*1000); 
  }
 /*end interval*/
 
/* UpperMessage */
function UpperMessage(){
    var self = this,
        element,
        hideAnim,
        showAnim,
        toggleButton,
        isHidden,
        elementHeight;
        
    this.onHideAnimComplete = new YAHOO.util.CustomEvent("onHideAnimComplete", this),
    this.onShowAnimComplete = new YAHOO.util.CustomEvent("onShowAnimComplete", this);
        
    this.init = function(cfg){
        element = YUD.get(cfg.elementId);
        toggleButton = YUD.get(cfg.toggleButtonId);
        elementHeight = cfg.elementHeight;
        hideAnim = new YAHOO.util.Anim(element, {height:{to: 0}}, 0.3, YAHOO.util.Easing.easeBoth);
        hideAnim.onComplete.subscribe(onHideAnimComplete);
        showAnim = new YAHOO.util.Anim(element, {height:{to: elementHeight}}, 0.3, YAHOO.util.Easing.easeBoth);
        showAnim.onComplete.subscribe(onShowAnimComplete);
        isHidden = cfg.isHidden;
    }
        
    this.hide = function(){
        hideAnim.animate();
    }
        
    this.show = function(){        
        showAnim.animate();
    }
    
    this.toggle = function(){
        if (isHidden){
            self.show();            
        }
        else{
            self.hide();
        }
    }
    
    this.getElementHeight = function(){
        return elementHeight;
    }
    
    var onHideAnimComplete = function(){
        YUD.replaceClass(toggleButton, "state_close", "state_open");
        isHidden = true;
        self.onHideAnimComplete.fire();
    }
    
    var onShowAnimComplete = function(){
        YUD.replaceClass(toggleButton, "state_open", "state_close");
        isHidden = false;
        self.onShowAnimComplete.fire();
    }
};

//YUE.addListener(window, "load", 
//    function()
//    {
//        itemManager.init
//        (
//            {
//                containerElId: "itemContainer",
//                onItemRatedGlobalFunction: onItemRated,
//                initialItems: itemCfgArr,
//                headerAndFooterHeight: 165,
//                linksToDisplay: 5
//            }
//        );
//        
//        upperMessage.init
//        (
//            {
//                elementId: "site_description",
//                toggleButtonId: "lnkToggleMessage",
//                elementHeight: 108,
//                isHidden: true
//            }
//        )
//    }
//);

function moveNoNews() {
    var elWrapper = YUD.get("noNews");
	var element = elWrapper.getElementsByTagName("p")[0];
	var linkButton = element.getElementsByTagName("a")[0];
	
    var moveAttributes = {
            top: {to: -1000},
            opacity: {to: 0}
        };
	var moveAnim = new YAHOO.util.Anim(element, moveAttributes, 0.7, YAHOO.util.Easing.easeIn); 
	moveAnim.animate();
	moveAnim.onComplete.subscribe(function(){
	    YUD.setStyle(elWrapper, "display", "none")
	});
}
//--------------------------------------------------------------
// Copyright (C) 2006 Michael Schwarz (http://www.ajaxpro.info).
// All rights reserved.
//--------------------------------------------------------------

// prototype.js
Object.extend = function(dest, source, replace) {
	for(var prop in source) {
		if(replace == false && dest[prop] != null) { continue; }
		dest[prop] = source[prop];
	}
	return dest;
};

Object.extend(Function.prototype, {
	apply: function(o, a) {
		var r, x = "__fapply";
		if(typeof o != "object") { o = {}; }
		o[x] = this;
		var s = "r = o." + x + "(";
		for(var i=0; i<a.length; i++) {
			if(i>0) { s += ","; }
			s += "a[" + i + "]";
		}
		s += ");";
		eval(s);
		delete o[x];
		return r;
	},
	bind: function(o) {
		if(!Function.__objs) {
			Function.__objs = [];
			Function.__funcs = [];
		}
		var objId = o.__oid;
		if(!objId) {
			Function.__objs[objId = o.__oid = Function.__objs.length] = o;
		}

		var me = this;
		var funcId = me.__fid;
		if(!funcId) {
			Function.__funcs[funcId = me.__fid = Function.__funcs.length] = me;
		}

		if(!o.__closures) {
			o.__closures = [];
		}

		var closure = o.__closures[funcId];
		if(closure) {
			return closure;
		}

		o = null;
		me = null;

		return Function.__objs[objId].__closures[funcId] = function() {
			return Function.__funcs[funcId].apply(Function.__objs[objId], arguments);
		};
	}
}, false);

Object.extend(Array.prototype, {
	push: function(o) {
		this[this.length] = o;
	},
	addRange: function(items) {
		if(items.length > 0) {
			for(var i=0; i<items.length; i++) {
				this.push(items[i]);
			}
		}
	},
	clear: function() {
		this.length = 0;
		return this;
	},
	shift: function() {
		if(this.length == 0) { return null; }
		var o = this[0];
		for(var i=0; i<this.length-1; i++) {
			this[i] = this[i + 1];
		}
		this.length--;
		return o;
	}
}, false);

Object.extend(String.prototype, {
	trimLeft: function() {
		return this.replace(/^\s*/,"");
	},
	trimRight: function() {
		return this.replace(/\s*$/,"");
	},
	trim: function() {
		return this.trimRight().trimLeft();
	},
	endsWith: function(s) {
		if(this.length == 0 || this.length < s.length) { return false; }
		return (this.substr(this.length - s.length) == s);
	},
	startsWith: function(s) {
		if(this.length == 0 || this.length < s.length) { return false; }
		return (this.substr(0, s.length) == s);
	},
	split: function(c) {
		var a = [];
		if(this.length == 0) return a;
		var p = 0;
		for(var i=0; i<this.length; i++) {
			if(this.charAt(i) == c) {
				a.push(this.substring(p, i));
				p = ++i;
			}
		}
		a.push(s.substr(p));
		return a;
	}
}, false);

Object.extend(String, {
	format: function(s) {
		for(var i=1; i<arguments.length; i++) {
			s = s.replace("{" + (i -1) + "}", arguments[i]);
		}
		return s;
	},
	isNullOrEmpty: function(s) {
		if(s == null || s.length == 0) {
			return true;
		}
		return false;
	}
}, false);

if(typeof addEvent == "undefined")
	addEvent = function(o, evType, f, capture) {
		if(o == null) { return false; }
		if(o.addEventListener) {
			o.addEventListener(evType, f, capture);
			return true;
		} else if (o.attachEvent) {
			var r = o.attachEvent("on" + evType, f);
			return r;
		} else {
			try{ o["on" + evType] = f; }catch(e){}
		}
	};
	
if(typeof removeEvent == "undefined")
	removeEvent = function(o, evType, f, capture) {
		if(o == null) { return false; }
		if(o.removeEventListener) {
			o.removeEventListener(evType, f, capture);
			return true;
		} else if (o.detachEvent) {
			o.detachEvent("on" + evType, f);
		} else {
			try{ o["on" + evType] = function(){}; }catch(e){}
		}
	};
//--------------------------------------------------------------
// Copyright (C) 2006 Michael Schwarz (http://www.ajaxpro.info).
// All rights reserved.
//--------------------------------------------------------------

// core.js
Object.extend(Function.prototype, {
	getArguments: function() {
		var args = [];
		for(var i=0; i<this.arguments.length; i++) {
			args.push(this.arguments[i]);
		}
		return args;
	}
}, false);

var MS = {"Browser":{}};

Object.extend(MS.Browser, {
	isIE: navigator.userAgent.indexOf('MSIE') != -1,
	isFirefox: navigator.userAgent.indexOf('Firefox') != -1,
	isOpera: window.opera != null
}, false);

var AjaxPro = {};

AjaxPro.IFrameXmlHttp = function() {};
AjaxPro.IFrameXmlHttp.prototype = {
	onreadystatechange: null, headers: [], method: "POST", url: null, async: true, iframe: null,
	status: 0, readyState: 0, responseText: null,
	abort: function() {
	},
	readystatechanged: function() {
		var doc = this.iframe.contentDocument || this.iframe.document;
		if(doc != null && doc.readyState == "complete" && doc.body != null && doc.body.res != null) {
			this.status = 200;
			this.statusText = "OK";
			this.readyState = 4;
			this.responseText = doc.body.res;
			this.onreadystatechange();
			return;
		}
		setTimeout(this.readystatechanged.bind(this), 10);
	},
	open: function(method, url, async) {
		if(async == false) {
			alert("Synchronous call using IFrameXMLHttp is not supported.");
			return;
		}
		if(this.iframe == null) {
			var iframeID = "hans";
			if (document.createElement && document.documentElement &&
				(window.opera || navigator.userAgent.indexOf('MSIE 5.0') == -1))
			{
				var ifr = document.createElement('iframe');
				ifr.setAttribute('id', iframeID);
				ifr.style.visibility = 'hidden';
				ifr.style.position = 'absolute';
				ifr.style.width = ifr.style.height = ifr.borderWidth = '0px';

				this.iframe = document.getElementsByTagName('body')[0].appendChild(ifr);
			}
			else if (document.body && document.body.insertAdjacentHTML)
			{
				document.body.insertAdjacentHTML('beforeEnd', '<iframe name="' + iframeID + '" id="' + iframeID + '" style="border:1px solid black;display:none"></iframe>');
			}
			if (window.frames && window.frames[iframeID]) {
				this.iframe = window.frames[iframeID];
			}
			this.iframe.name = iframeID;
			this.iframe.document.open();
			this.iframe.document.write("<html><body></body></html>");
			this.iframe.document.close();
		}
		this.method = method;
		this.url = url;
		this.async = async;
	},
	setRequestHeader: function(name, value) {
		for(var i=0; i<this.headers.length; i++) {
			if(this.headers[i].name == name) {
				this.headers[i].value = value;
				return;
			}
		}
		this.headers.push({"name":name,"value":value});
	},
	getResponseHeader: function(name, value) {
		return null;
	},
	addInput: function(doc, form, name, value) {
		var ele;
		var tag = "input";
		if(value.indexOf("\n") >= 0) {
			tag = "textarea";
		}
		
		if(doc.all) {
			ele = doc.createElement("<" + tag + " name=\"" + name + "\" />");
		}else{
			ele = doc.createElement(tag);
			ele.setAttribute("name", name);
		}
		ele.setAttribute("value", value);
		form.appendChild(ele);
		ele = null;
	},
	send: function(data) {
		if(this.iframe == null) {
			return;
		}
		var doc = this.iframe.contentDocument || this.iframe.document;
		var form = doc.createElement("form");
		
		doc.body.appendChild(form);
		
		form.setAttribute("action", this.url);
		form.setAttribute("method", this.method);
		form.setAttribute("enctype", "application/x-www-form-urlencoded");
		
		for(var i=0; i<this.headers.length; i++) {
			switch(this.headers[i].name.toLowerCase()) {
				case "content-length":
				case "accept-encoding":
				case "content-type":
					break;
				default:
					this.addInput(doc, form, this.headers[i].name, this.headers[i].value);
			}
		}
		this.addInput(doc, form, "data", data);
		form.submit();
		
		setTimeout(this.readystatechanged.bind(this), 0);
	}
};

var progids = ["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"];
var progid = null;

if(typeof ActiveXObject != "undefined") {
	var ie7xmlhttp = false;
	if(typeof XMLHttpRequest == "object") {
		try{ var o = new XMLHttpRequest(); ie7xmlhttp = true; }catch(e){}
	}
	if(typeof XMLHttpRequest == "undefined" || !ie7xmlhttp) {
		XMLHttpRequest = function() {
			var xmlHttp = null;
			if(!AjaxPro.noActiveX) {
				if(progid != null) {
					return new ActiveXObject(progid);
				}
				for(var i=0; i<progids.length && xmlHttp == null; i++) {
					try {
						xmlHttp = new ActiveXObject(progids[i]);
						progid = progids[i];

					}catch(e){}
				}
			}
			if(xmlHttp == null && MS.Browser.isIE) {
				return new AjaxPro.IFrameXmlHttp();
			}
			return xmlHttp;
		};
	}
}

Object.extend(AjaxPro, {
	noOperation: function() {},
	onLoading: function() {},
	onError: function() {},
	onTimeout: function() {},
	onStateChanged: function() {},
	cryptProvider: null,
	queue: null,
	token: "",
	version: "6.9.29.2",
	ID: "AjaxPro",
	noActiveX: false,
	timeoutPeriod: 10*1000,
	queue: null,
	noUtcTime: false,

	toJSON: function(o) {	
		if(o == null) {
			return "null";
		}
		var v = [];
		var i;
		var c = o.constructor;
		if(c == Number) {
				return isFinite(o) ? o.toString() : AjaxPro.toJSON(null);
		} else if(c == Boolean) {
				return o.toString();
		} else if(c == String) {
				for(i=0; i<o.length; i++) {
					var c = o.charAt(i);
					if(c >= " ") {
						if(c == "\\" || c == '"') {
							v.push("\\");
						}
						v.push(c);
					} else {
						switch(c) {
							case "\n": v.push("\\n"); break;
							case "\r": v.push("\\r"); break;
							case "\b": v.push("\\b"); break;
							case "\f": v.push("\\f"); break;
							case "\t": v.push("\\t"); break;
							default:
								v.push("\\u00");
								v.push(c.charCodeAt().toString(16));
						}
					}
				}
				return '"' + v.join('') + '"';
		} else if (c == Array) {
				for(i=0; i<o.length; i++) {
					v.push(AjaxPro.toJSON(o[i]));
				}
				return "[" + v.join(",") + "]";
		} else if (c == Date) {
				var d = {};
				d.__type = "System.DateTime";
				if(AjaxPro.noUtcTime == true) {
					d.Year = o.getFullYear();
					d.Month = o.getMonth() +1;
					d.Day = o.getDate();
					d.Hour = o.getHours();
					d.Minute = o.getMinutes();
					d.Second = o.getSeconds();
					d.Millisecond = o.getMilliseconds();
				} else {
					d.Year = o.getUTCFullYear();
					d.Month = o.getUTCMonth() +1;
					d.Day = o.getUTCDate();
					d.Hour = o.getUTCHours();
					d.Minute = o.getUTCMinutes();
					d.Second = o.getUTCSeconds();
					d.Millisecond = o.getUTCMilliseconds();
				}
				return AjaxPro.toJSON(d);
		}
		if(typeof o.toJSON == "function") {
			return o.toJSON();
		}
		if(typeof o == "object") {
			for(var attr in o) {
				if(typeof o[attr] != "function") {
					v.push('"' + attr + '":' + AjaxPro.toJSON(o[attr]));
				}
			}
			if(v.length>0) {
				return "{" + v.join(",") + "}";
			}
			return "{}";		
		}
		return o.toString();
	},
	dispose: function() {
		if(AjaxPro.queue != null) {
			AjaxPro.queue.dispose();
		}
	}
}, false);

addEvent(window, "unload", AjaxPro.dispose);

AjaxPro.Request = function(url) {
	this.url = url;
	this.xmlHttp = null;
};

AjaxPro.Request.prototype = {
	url: null,
	callback: null,
	onLoading: AjaxPro.noOperation,
	onError: AjaxPro.noOperation,
	onTimeout: AjaxPro.noOperation,
	onStateChanged: AjaxPro.noOperation,
	args: null,
	context: null,
	isRunning: false,
	abort: function() {
		if(this.timeoutTimer != null) {
			clearTimeout(this.timeoutTimer);
		}
		if(this.xmlHttp) {
			this.xmlHttp.onreadystatechange = AjaxPro.noOperation;
			this.xmlHttp.abort();
		}
		if(this.isRunning) {
			this.isRunning = false;
			this.onLoading(false);
		}
	},
	dispose: function() {
		this.abort();
	},
	getEmptyRes: function() {
		return {
			error: null,
			value: null,
			request: {method:this.method, args:this.args},
			context: this.context,
			duration: this.duration
		};	
	},
	endRequest: function(res) {
		this.abort();
		if(res.error != null) {
			this.onError(res.error, this);
		}

		if(typeof this.callback == "function") {
			this.callback(res, this);
		}
	},
	mozerror: function() {
		if(this.timeoutTimer != null) {
			clearTimeout(this.timeoutTimer);
		}
		var res = this.getEmptyRes();
		res.error = {Message:"Unknown",Type:"ConnectFailure",Status:0};
		this.endRequest(res);
	},
	doStateChange: function() {
		this.onStateChanged(this.xmlHttp.readyState, this);

		if(this.xmlHttp.readyState != 4 || !this.isRunning) {
			return;
		}

		this.duration = new Date().getTime() - this.__start;

		if(this.timeoutTimer != null) {
			clearTimeout(this.timeoutTimer);
		}

		var res = this.getEmptyRes();
		if(this.xmlHttp.status == 200 && this.xmlHttp.statusText == "OK") {
			res = this.createResponse(res);
		} else {
			res = this.createResponse(res, true);
			res.error = {Message:this.xmlHttp.statusText,Type:"ConnectFailure",Status:this.xmlHttp.status};
		}
		
		this.endRequest(res);
	},
	createResponse: function(r, noContent) {	
		if(!noContent) {
			var responseText = "" + this.xmlHttp.responseText;

			if(AjaxPro.cryptProvider != null && typeof AjaxPro.cryptProvider == "function") {
				responseText = AjaxPro.cryptProvider.decrypt(responseText);
			}

			if(this.xmlHttp.getResponseHeader("Content-Type") == "text/xml") {
				r.value = this.xmlHttp.responseXML;
			} else {
				if(responseText != null && responseText.trim().length > 0) {
					r.json = responseText;
					eval("r.value = " + responseText + "*" + "/");
				}
			}
		}
		/* if(this.xmlHttp.getResponseHeader("X-" + AjaxPro.ID + "-Cache") == "server") {
			r.isCached = true;
		} */
		return r;
	},
	timeout: function() {
		this.duration = new Date().getTime() - this.__start;
		var r = this.onTimeout(this.duration, this);
		if(typeof r == "undefined" || r != false) {
			this.abort();
		} else {
			this.timeoutTimer = setTimeout(this.timeout.bind(this), AjaxPro.timeoutPeriod);
		}
	},
	invoke: function(method, args, callback, context) {
		this.__start = new Date().getTime();

		if(this.xmlHttp == null) {
			this.xmlHttp = new XMLHttpRequest();
		}

		this.isRunning = true;
		this.method = method;
		this.args = args;
		this.callback = callback;
		this.context = context;
		
		var async = typeof(callback) == "function" && callback != AjaxPro.noOperation;
		
		if(async) {
			if(MS.Browser.isIE) {
				this.xmlHttp.onreadystatechange = this.doStateChange.bind(this);
			} else {
				this.xmlHttp.onload = this.doStateChange.bind(this);
				this.xmlHttp.onerror = this.mozerror.bind(this);
			}
			this.onLoading(true);
		}
		
		var json = AjaxPro.toJSON(args) + "";
		if(AjaxPro.cryptProvider != null) {
			json = AjaxPro.cryptProvider.encrypt(json);
		}
		
		this.xmlHttp.open("POST", this.url, async);
		this.xmlHttp.setRequestHeader("Content-Type", "text/plain; charset=utf-8");
		this.xmlHttp.setRequestHeader("X-" + AjaxPro.ID + "-Method", method);
		
		if(AjaxPro.token != null && AjaxPro.token.length > 0) {
			this.xmlHttp.setRequestHeader("X-" + AjaxPro.ID + "-Token", AjaxPro.token);
		}

		if(!MS.Browser.isIE) {
			this.xmlHttp.setRequestHeader("Connection", "close");		// Mozilla Bug #246651
		}

		this.timeoutTimer = setTimeout(this.timeout.bind(this), AjaxPro.timeoutPeriod);

		try{ this.xmlHttp.send(json); }catch(e){}	// IE offline exception

		if(!async) {
			return this.createResponse({error: null,value: null});
		}

		return true;	
	}
};

AjaxPro.RequestQueue = function(conc) {
	this.queue = [];
	this.requests = [];
	this.timer = null;
	
	if(isNaN(conc)) { conc = 2; }

	for(var i=0; i<conc; i++) {		// max 2 http connections
		this.requests[i] = new AjaxPro.Request();
		this.requests[i].callback = function(res) {
			var r = res.context;
			res.context = r[3][1];

			r[3][0](res, this);
		};
		this.requests[i].callbackHandle = this.requests[i].callback.bind(this.requests[i]);
	}
};

AjaxPro.RequestQueue.prototype = {
	process: function() {
	
		this.timer = null;
		if(this.queue.length == 0) {
			return;
		}
		for(var i=0; i<this.requests.length && this.queue.length > 0; i++) {
			if(this.requests[i].isRunning == false) {
				var r = this.queue.shift();

				this.requests[i].url = r[0];
				this.requests[i].onLoading = r[3].length >2 && r[3][2] != null && typeof r[3][2] == "function" ? r[3][2] : AjaxPro.onLoading;
				this.requests[i].onError = r[3].length >3 && r[3][3] != null && typeof r[3][3] == "function" ? r[3][3] : AjaxPro.onError;
				this.requests[i].onTimeout = r[3].length >4 && r[3][4] != null && typeof r[3][4] == "function" ? r[3][4] : AjaxPro.onTimeout;
				this.requests[i].onStateChanged = r[3].length >5 && r[3][5] != null && typeof r[3][5] == "function" ? r[3][5] : AjaxPro.onStateChanged;

				this.requests[i].invoke(r[1], r[2], this.requests[i].callbackHandle, r);
				r = null;
			}
		}
		if(this.queue.length > 0 && this.timer == null) {
			this.timer = setTimeout(this.process.bind(this), 0);
		}
	},
	add: function(url, method, args, e) {

// txt += "\r\nqueue.add " + (new Date().getTime() - ss);

		this.queue.push([url, method, args, e]);
/*		
		if(this.timer == null) {
			this.timer = setTimeout(this.process.bind(this), 0);
		}
*/
		this.process();
	},
	abort: function() {
		this.queue.length = 0;
		if (this.timer != null) {
			clearTimeout(this.timer);
		}
		this.timer = null;
		for(var i=0; i<this.requests.length; i++) {
			if(this.requests[i].isRunning == true) {
				this.requests[i].abort();
			}
		}
	},
	dispose: function() {
		for(var i=0; i<this.requests.length; i++) {
			var r = this.requests[i];
			r.dispose();
		}
		this.requests.clear();
	}
};

AjaxPro.queue = new AjaxPro.RequestQueue(2);	// 2 http connections

AjaxPro.AjaxClass = function(url) {
	this.url = url;
};

AjaxPro.AjaxClass.prototype = {
	invoke: function(method, args, e) {
	
		if(e != null) {
			if(e.length != 6) {
				for(;e.length<6;) { e.push(null); }
			}
			if(e[0] != null && typeof(e[0]) == "function") {
				return AjaxPro.queue.add(this.url, method, args, e);
			}
		}
		var r = new AjaxPro.Request();
		r.url = this.url;
		return r.invoke(method, args);
	}
};
//--------------------------------------------------------------
// Copyright (C) 2006 Michael Schwarz (http://www.ajaxpro.info).
// All rights reserved.
//--------------------------------------------------------------
// Converter.js

// NameValueCollectionConverter
if(typeof Ajax == "undefined") Ajax={};
if(typeof Ajax.Web == "undefined") Ajax.Web={};

Ajax.Web.NameValueCollection = function(items) {
	this.__type = "System.Collections.Specialized.NameValueCollection";
	this.keys = [];
	this.values = [];

	if(items != null && !isNaN(items.length)) {
		for(var i=0; i<items.length; i++)
			this.add(items[i][0], items[i][1]);
	}
};
Object.extend(Ajax.Web.NameValueCollection.prototype, {
	add: function(k, v) {
		if(k == null || k.constructor != String || v == null || v.constructor != String)
			return -1;
		this.keys.push(k);
		this.values.push(v);
		return this.values.length -1;
	},
	containsKey: function(key) {
		for(var i=0; i<this.keys.length; i++) {
			if(this.keys[i] == key) return true;
		}
		return false;
	},
	getKeys: function() {
		return this.keys;
	},
	getValue: function(k) {
		for(var i=0; i<this.keys.length && i<this.values.length; i++) {
			if(this.keys[i] == k) return this.values[i];
		}
		return null;
	},
	setValue: function(k, v) {
		if(k == null || k.constructor != String || v == null || v.constructor != String)
			return -1;
		for(var i=0; i<this.keys.length && i<this.values.length; i++) {
			if(this.keys[i] == k) this.values[i] = v;
			return i;
		}
		return this.add(k, v);
	},
	toJSON: function() {
		return AjaxPro.toJSON({__type:this.__type,keys:this.keys,values:this.values});
	}
}, true);

// DataSetConverter
if(typeof Ajax == "undefined") Ajax={};
if(typeof Ajax.Web == "undefined") Ajax.Web={};

Ajax.Web.DataSet = function(t) {
	this.__type = "System.Data.DataSet,System.Data";
	this.Tables = [];
	this.addTable = function(t) {
		this.Tables.push(t);
	};
	if(t != null) {
		for(var i=0; i<t.length; i++) {
			this.addTable(t[i]);
		}
	}
};

// DataTableConverter
if(typeof Ajax == "undefined") Ajax={};
if(typeof Ajax.Web == "undefined") Ajax.Web={};

Ajax.Web.DataTable = function(c, r) {
	this.__type = "System.Data.DataTable,System.Data";
	this.Columns = [];
	this.Rows = [];
	this.addColumn = function(name, type) {
		this.Columns.push({Name:name,__type:type});
	};
	this.toJSON = function() {
		var dt = {};
		var i;
		dt.Columns = [];
		for(i=0; i<this.Columns.length; i++)
			dt.Columns.push([this.Columns[i].Name, this.Columns[i].__type]);
		dt.Rows = [];
		for(i=0; i<this.Rows.length; i++) {
			var row = [];
			for(var j=0; j<this.Columns.length; j++)
				row.push(this.Rows[i][this.Columns[j].Name]);
			dt.Rows.push(row);
		}
		return AjaxPro.toJSON(dt);
	};
	this.addRow = function(row) {
		this.Rows.push(row);
	};
	if(c != null) {
		for(var i=0; i<c.length; i++)
			this.addColumn(c[i][0], c[i][1]);
	}
	if(r != null) {
		for(var y=0; y<r.length; y++) {
			var row = {};
			for(var z=0; z<this.Columns.length && z<r[y].length; z++)
				row[this.Columns[z].Name] = r[y][z];
			this.addRow(row);
		}
	}
};

// ProfileBaseConverter
if(typeof Ajax == "undefined") Ajax={};
if(typeof Ajax.Web == "undefined") Ajax.Web={};

Ajax.Web.Profile = function() {
	this.toJSON = function() {
		throw "Ajax.Web.Profile cannot be converted to JSON format.";
	};
	this.setProperty_callback = function(res) {
	};
	this.setProperty = function(name, object) {
		this[name] = object;
		AjaxPro.Services.Profile.SetProfile({name:o}, this.setProperty_callback.bind(this));
	};
};

// IDictionaryConverter
if(typeof Ajax == "undefined") Ajax={};
if(typeof Ajax.Web == "undefined") Ajax.Web={};

Ajax.Web.Dictionary = function(type,items) {
	this.__type = type;
	this.keys = [];
	this.values = [];

	if(items != null && !isNaN(items.length)) {
		for(var i=0; i<items.length; i++)
			this.add(items[i][0], items[i][1]);
	}
};
Object.extend(Ajax.Web.Dictionary.prototype, {
	add: function(k, v) {
		this.keys.push(k);
		this.values.push(v);
		return this.values.length -1;
	},
	containsKey: function(key) {
		for(var i=0; i<this.keys.length; i++) {
			if(this.keys[i] == key) return true;
		}
		return false;
	},
	getKeys: function() {
		return this.keys;
	},
	getValue: function(key) {
		for(var i=0; i<this.keys.length && i<this.values.length; i++) {
			if(this.keys[i] == key){ return this.values[i]; }
		}
		return null;
	},
	setValue: function(k, v) {
		for(var i=0; i<this.keys.length && i<this.values.length; i++) {
			if(this.keys[i] == k){ this.values[i] = v; }
			return i;
		}
		return this.add(k, v);
	},
	toJSON: function() {
		return AjaxPro.toJSON({__type:this.__type,keys:this.keys,values:this.values});
	}
}, true);