var iNettuts = {
    
    jQuery : $,
    
    settings : {
        columns : '.column',
        widgetSelector: '.widget',
        handleSelector: '.widget-head',
        contentSelector: '.widget-content',
		rssItems : ['הכל','1','3','5','7','10','15','20'],
		rssInvterval : ['60|דקה','180|3 דקות','300|5 דקות','420|7 דקות','600|10 דקות','900|15 דקות','1200|20 דקות','1800|30 דקות'],
        saveToCookie: 'torec-mainCookie',
        widgetDefault : {
            movable: true,
            removable: true,
            collapsible: true,
            editable: true,
            colorClasses : ['color-yellow', 'color-orange', 'color-red', 'color-darkred', 'color-blue', 'color-blue2', 'color-blue3', 'color-white', 'color-white2', 'color-green', 'color-green2', 'color-green3', 'color-brown', 'color-purple', 'color-purple2', 'color-purple3', 'color-black', 'break',
							'color-blue4', 'color-purple4', 'color-white3', 'color-darkred2', 'color-yellow2', 'color-green4', 'color-brown2', 'color-black2']
        },
        widgetIndividual : {
            info_torec : {
                movable: true,
                removable: true,
                collapsible: true,
                editable: false
			}
		}
    },

    init : function () {
        this.attachStylesheet('/js/inettuts/inettuts.js.css');
        this.addWidgetControls();
        this.makeSortable();
		$('.collapsed .collapse').html('<img src="/JS/inettuts/img/down_arrow.png" alt="הצגת תוכן" style="Border:0;" />');
    },
    
    getWidgetSettings : function (id) {
        var $ = this.jQuery,
            settings = this.settings;
        return (id&&settings.widgetIndividual[id]) ? $.extend({},settings.widgetDefault,settings.widgetIndividual[id]) : settings.widgetDefault;
    },
    
    refreshWidgetContent : function (contentObj) {
        var iNettuts = this,
            $ = this.jQuery,
            settings = this.settings,
			intervalTime = (contentObj.attr('interval')*1000)+(Math.round(Math.random()*(contentObj.attr('url').length-contentObj.attr('items'))));
		$("#"+contentObj.attr('id')).stopTime();
		$("#"+contentObj.attr('id')).everyTime(intervalTime,function(i){
			$('#'+contentObj.attr('id')+' '+settings.handleSelector+' .refresh').click();
		})
    },
    
    addWidgetControls : function () {
        var iNettuts = this,
            $ = this.jQuery,
            settings = this.settings;
            
        $(settings.widgetSelector, $(settings.columns)).each(function () {
            var thisWidgetSettings = iNettuts.getWidgetSettings(this.id);
            if (thisWidgetSettings.removable) {
                $('<a href="#" class="remove">סגור</a>').mousedown(function (e) {
                    /* STOP event bubbling */
                    e.stopPropagation();    
                }).click(function () {
                    if(confirm('האם ברצונך לסגור את התיבה הנוכחית?')) {
                        $(this).parents(settings.widgetSelector).animate({
                            opacity: 0    
                        },function () {
                            $(this).wrap('<div/>').parent().slideUp(function () {
                                $(this).remove();
								iNettuts.savePreferences();
                            });
                        });
                    }
                    return false;
                }).appendTo($(settings.handleSelector, this));
            }
            
            if (thisWidgetSettings.editable) {
                $('<a href="#" class="edit">עריכה</a>').mousedown(function (e) {
                    /* STOP event bubbling */
                    e.stopPropagation();    
                }).toggle(function () {
                    $(this).parents(settings.widgetSelector)
                            .find('.edit-box').show().find('input.boxTitlte').focus();
					$(this).parents(settings.widgetSelector).find('.totalItemsRSS').html($(this).parents(settings.widgetSelector).find('.totalItems').html());

                    return false;
                },function () {
                    $(this).css({backgroundPosition: '', width: '24px'})
                        .parents(settings.widgetSelector)
                            .find('.edit-box').hide();
                    return false;
                }).appendTo($(settings.handleSelector,this));
				// RSS BOX
				if($('#'+this.id).hasClass('rss')) {
					var rssItems_curr = $('#'+this.id).attr('items');
					var rssItems_text = '<li class="item"><label>מס\' פריטים:</label><select class="itemsNum">';
					$(iNettuts.settings.rssItems).each(function () {
							if(this==rssItems_curr)
								rssItems_text += '<option value="' + this + '"" selected="selected">' + this + '</option>';
							else
								rssItems_text += '<option value="' + this + '"">' + this + '</option>';
                    });
					rssItems_text += '</select> מתוך <span class="totalItemsRSS"></span></li>'; 
					
					
					var rssInterval_curr = $('#'+this.id).attr('interval');
					rssItems_text += '<li class="item"><label>קצב רענון:</label><select class="itemsInterval">';
					$(iNettuts.settings.rssInvterval).each(function () {
							thisInterval = this.split('|');
							if(thisInterval[0]==rssInterval_curr)
								rssItems_text += '<option value="' + thisInterval[0] + '"" selected="selected">' + thisInterval[1] + '</option>';
							else
								rssItems_text += '<option value="' + thisInterval[0] + '"">' + thisInterval[1] + '</option>';
                    });
					rssItems_text += '</select></li>';
				}
				else
					var rssItems_text = "";
                $('<div class="edit-box" style="display:none;"/>')
                    .append('<ul><li class="item"><label>כותרת:</label><input value="' + $('h3',this).text().replace(/"/g,'&#34;') + '" class="boxTitlte"/> </li>')
					.append(rssItems_text)
                    .append((function(){
                        var colorList = '<li class="item"><label>עיצוב בסיסי:</label><ul class="colors">';
                        $(thisWidgetSettings.colorClasses).each(function () {
							if(this=='break' && rssItems_text=="")
								return false;
							else if (this=='break')
								colorList += '</ul><li class="item"><label>עיצוב מלא:</label><ul class="colors">';
							else
								colorList += '<li class="' + this + '"/>';
                        });
                        return colorList + '</ul>';
                    })())
                    .append('</ul>')
                    .insertAfter($(settings.handleSelector,this));
					if($('#'+this.id).hasClass('rss'))
						iNettuts.refreshWidgetContent($('#'+this.id));
            }

            if ($('#'+this.id).hasClass('rss')) {
                $('<a href="#" class="refresh">רענן</a>').mousedown(function (e) {
                    /* STOP event bubbling */
                    e.stopPropagation();    
                }).click(function () {
					var contentID = '#'+$(this).parents(settings.widgetSelector).attr('id')+' '+settings.contentSelector;
					if($(contentID).html()=='<img src="/images/sloading.gif" alt="טוען" style="margin:0;border:0;float:left;" />')
						$(contentID).html('<img src="/images/sloading.gif" alt="טוען" style="margin:0;border:0;float:left;" />');
					else
						$(contentID).html('<img src="/images/sloading.gif" alt="טוען" style="margin:0;border:0;float:left;" />'+$(contentID).html());
					readRSS($(this).parents(settings.widgetSelector).attr('id'),$(this).parents(settings.widgetSelector).attr('url'),$(this).parents(settings.widgetSelector).attr('items'));
                    return false;
                }).appendTo($(settings.handleSelector, this));
            }
			
            if($('#'+this.id).attr('icon'))
				var widget_icon = '<img src="'+$('#'+this.id).attr('icon')+'" onerror="this.src=\'/JS/inettuts/img/no-icon.png\'" />';
			else
				var widget_icon = '<img src="/JS/inettuts/img/no-icon.png" />';
            $('<div class="icon">'+widget_icon+'</div>').prependTo($(settings.handleSelector,this));

            if (thisWidgetSettings.collapsible) {
                $('<a href="#" class="collapse"><img src="/JS/inettuts/img/up_arrow.png" alt="הסתרת תוכן" style="Border:0;" /></a>').mousedown(function (e) {
                    /* STOP event bubbling */
                    e.stopPropagation();
                }).click(function(){
					if($(this).html().indexOf('הסתרת תוכן')!=-1)
						$(this).html('<img src="/JS/inettuts/img/down_arrow.png" alt="הצגת תוכן" style="Border:0;" />');
					else
						$(this).html('<img src="/JS/inettuts/img/up_arrow.png" alt="הסתרת תוכן" style="Border:0;" />');
                    $(this).parents(settings.widgetSelector).toggleClass('collapsed');
                    iNettuts.savePreferences();
                    return false;    
                }).prependTo($(settings.handleSelector,this));
            }
			$('#'+this.id+' '+settings.handleSelector+' a').css('display','none'); //הסתרת ניהול תיבה
        });
        
        $('.edit-box').each(function () {
            $('input.boxTitlte',this).keyup(function () {
                $(this).parents(settings.widgetSelector).find('h3').text( $(this).val().length>50 ? $(this).val().substr(0,50)+'...' : $(this).val() );
                iNettuts.savePreferences();
            });
            $('ul.colors li',this).click(function () {
                
                var colorStylePattern = /\bcolor-[\w]{1,}\b/,
                    thisWidgetColorClass = $(this).parents(settings.widgetSelector).attr('class').match(colorStylePattern)
                if (thisWidgetColorClass) {
                    $(this).parents(settings.widgetSelector)
                        .removeClass(thisWidgetColorClass[0])
                        .addClass($(this).attr('class').match(colorStylePattern)[0]);
                    $('#'+$(this).parents(settings.widgetSelector).attr('id')+' '+settings.contentSelector)
                        .removeClass(thisWidgetColorClass[0]+'_content')
                        .addClass($(this).attr('class')+'_content');
					
                    iNettuts.savePreferences();
                }
                return false;
                
            });
            $('select.itemsNum',this).change(function () {
				$(this).parents(settings.widgetSelector).attr('items',$('#'+$(this).parents(settings.widgetSelector).attr('id')+' .itemsNum option:selected').val().replace('הכל','100'));
				$('#'+$(this).parents(settings.widgetSelector).attr('id')+' '+settings.handleSelector+' .refresh').click();
				iNettuts.savePreferences();
            });
            $('select.itemsInterval',this).change(function () {
				$(this).parents(settings.widgetSelector).attr('interval',$('#'+$(this).parents(settings.widgetSelector).attr('id')+' .itemsInterval option:selected').val());
				iNettuts.refreshWidgetContent($(this).parents(settings.widgetSelector));
				iNettuts.savePreferences();
            });
        });
        
    },
    
    attachStylesheet : function (href) {
        var $ = this.jQuery;
        return $('<link href="' + href + '" rel="stylesheet" type="text/css" />').appendTo('head');
    },
    
    makeSortable : function () {
        var iNettuts = this,
            $ = this.jQuery,
            settings = this.settings,
            $sortableItems = (function () {
                var notSortable = null;
                $(settings.widgetSelector,$(settings.columns)).each(function (i) {
               
					if (!iNettuts.getWidgetSettings(this.id).movable) {
                        if(!this.id) {
                            this.id = 'widget-no-id-' + i;
                        }
                        notSortable += '#' + this.id + ',';
                    }
                });
                return $('> li:not(' + notSortable + ')', settings.columns);
            })();
        
        $sortableItems.find(settings.handleSelector).css({
            cursor: 'move'
        }).mouseover(function() {
			$('#'+$(this).parent().attr('id')+' '+settings.handleSelector+' a').css('display','');
			$('#'+$(this).parent().attr('id')+' '+settings.handleSelector+' .icon').css('display','none');
		}).mouseout(function() {
			$('#'+$(this).parent().attr('id')+' '+settings.handleSelector+' a').css('display','none');
			$('#'+$(this).parent().attr('id')+' '+settings.handleSelector+' .icon').css('display','');
		}).mousedown(function (e) {
            $sortableItems.css({width:''});
            $(this).parent().css({
                width: $(this).parent().width() + 'px'
            });
        }).mouseup(function () {
            if(!$(this).parent().hasClass('dragging')) {
                $(this).parent().css({width:''});
            } else {
                $(settings.columns).sortable('disable');
            }
        });

        $(settings.columns).sortable({
            items: $sortableItems,
            connectWith: $(settings.columns),
            handle: settings.handleSelector,
            placeholder: 'widget-placeholder',
            forcePlaceholderSize: true,
            revert: 300,
            delay: 0,
            opacity: 0.8,
            containment: 'document',
            start: function (e,ui) {
                $(ui.helper).addClass('dragging');
            },
            stop: function (e,ui) {
                $(ui.item).css({width:''}).removeClass('dragging');
                $(settings.columns).sortable('enable');
                iNettuts.savePreferences();
            }
        });
    },
    
    savePreferences : function () {
        var iNettuts = this,
            $ = this.jQuery,
            settings = this.settings,
            cookieString = '',
			cookieStringOrder='',
			cancelFullScreen=false;
        if(!settings.saveToCookie) {return;}
        /* Assemble the cookie string */
        $(settings.columns).each(function(i){
            cookieString += (i===0) ? '' : '|';
            cookieStringOrder += $(this).attr('id')+',';
            $(settings.widgetSelector,this).each(function(i){
                cookieString += (i===0) ? '' : ';;';
                /* ID of widget: */
                cookieString += $(this).attr('id') + ',';
                /* Color of widget (color classes) */
                cookieString += $(this).attr('class').match(/\bcolor-[\w]{1,}\b/) + ',';
                /* Title of widget (replaced used characters) */
                cookieString += $('h3:eq(0)',this).text().replace(/\|/g,'[-PIPE-]').replace(/,/g,'[-COMMA-]') + ',';
                /* Collapsed/not collapsed widget? : */
                cookieString += $(settings.contentSelector,this).css('display') === 'none' ? 'collapsed' + ',' : 'not-collapsed' + ',';
				if($(this).attr('icon')) {cookieString += $(this).attr('icon') + ',';} else {cookieString += ','};
				if($(this).attr('url')) {cookieString += $(this).attr('url') + ',';} else {cookieString += ','};
				if($(this).attr('interval')) {cookieString += $(this).attr('interval') + ',';} else {cookieString += ','};
				if($(this).attr('items')) {cookieString += $(this).attr('items');} else {cookieString += ''};
            });
        });
		if($('#cancelFS').length!=0)
			cancelFullScreen = $('#cancelFS').html();
		$('#ttt').html(cookieString+'\n\n'+cookieStringOrder);
		$.post("/ajax/main/cookieUpdate.asp", { cookies: cookieString, order: cookieStringOrder, cancelFS: cancelFullScreen } ,function() {
			if(cancelFullScreen)
				location.href = location.href;
			}
		);
    }
  
};

function insertWidget(type,where, opt) {
	var addContentTo = $('#addContentTo option:selected').val();
	var selectorOld = iNettuts.settings.widgetSelector;
	iNettuts.settings.widgetSelector = '.new'+opt.num;
	if(opt.content.indexOf('widget-content')==-1)
		opt.content = '<div class="widget-content">'+opt.content+'</div>';
	if(type=="rss")
		opt.color += " rss";
	opt.content = opt.content.replace('widget-content','widget-content color-'+opt.color+'_content');
	var boxdata = '<li class="new'+opt.num+' widget color-'+opt.color+'" id="'+opt.id+'" icon="'+opt.icon+'" url="'+opt.url+'" interval="'+opt.interval+'" items="'+opt.items+'"><div class="widget-head"><h3>'+opt.title+'</h3></div>'+opt.content+'</li>';
	if(addContentTo!="default")
		where = '#'+addContentTo;
	$(where).append(boxdata);
	iNettuts.addWidgetControls();
    $(iNettuts.settings.columns).sortable('destroy');
	iNettuts.makeSortable();
	iNettuts.settings.widgetSelector = selectorOld;
	$(".new"+opt.num).corner("5px");
	iNettuts.savePreferences();
}

function addBox(bid,url,where,opt) {
	type = "";
	if($('#'+bid).length!=0) {
		addBox_alreadyADDED();
	}
	else {
		if(url.indexOf('.asp')==-1)
			url = '/ajax/main/box/'+bid+'.asp';
		else if(url.indexOf('drss')!=-1)
			type = "rss";
		$.get(url,function(data) {
			opt.content = data;
			opt.id = bid;
			insertWidget(type,where, opt);
		});
	}
}

function addBox_alreadyADDED() {
		$.weeboxs.open('התוכן הרצוי להוספה כבר קיים בעמוד.',{type:'error',title:'שגיאה: הוספת תוכן',showCancel:false});
}

function makeRSSToolTip(obj) {
	$(document).ready(function(){
		tcontent = $('#'+obj+'_content').html();
		$('#'+obj).wTooltip({
				content: tcontent,
				className: 'tooltip',
				offsetY: 30,
				offsetX: -150,
				style: {width:"330px",padding:"6px",fontSize:"13px"}
		  });
	});
}

function readRSS(id,url,numItems) {
	$(document).ready(function(){
		url = url.replace('&','||');
		$.ajax({
			type: "GET",
			data: {rssurl: url},
			url: '/functions/js_ReadRSS.asp',
			dataType: "xml",
			success: function(xml) {
				var i=1,
					html = '<ul>',html2='',hscript='',
					title='',description='',link='',uID='',
					mydate=new Date();
				$(xml).find('item').each(function(){
					uID = url.replace('http://','').replace(/./g,'')+'/';
					uID = url.replace('http://','').replace('.','')+'/';
					while(uID.indexOf('.')!=-1)
						uID = uID.replace('.','');
					uID = uID.substr(0,uID.indexOf('/'));
					uID += '_'+mydate.getYear()+mydate.getDay()+mydate.getMonth()+mydate.getHours()+mydate.getMinutes()+mydate.getSeconds()+i;
					title = $(this).find('title').text();
					link = $(this).find('link').text();
					description = readRSS_desc($(this).find('description').text());
					html +='<li>'+i+'. <a href="'+link+'" id="'+uID+'" target="_blank">'+title+'</a></li>';
					if(description!=false) {
						html2+= '<span id="'+uID+'_content" style="display:none;">'+description+'</span>';
						hscript+= 'makeRSSToolTip("'+uID+'");';
					}
					if(i==numItems)
						return false;
					i++;
				});
				if(hscript.length>0)
					hscript = '<script>'+hscript+'</script>';
				$('#'+id+' .widget-content').html(html+'</ul><span class="totalItems">'+$(xml).find('item').size()+'</span>'+html2+hscript);
				//alert(hscript);
			}
		});
	});
}
function readRSS_desc(desc) {
	if(desc=='undefined')
		return false;
	return desc;
}
