/*
 * Script from NETTUTS.com [by James Padolsey] V.2 (ENHANCED, WITH COOKIES!!!)
 * @requires jQuery($), jQuery UI & sortable/draggable UI modules & jQuery COOKIE plugin
 */

var iNettuts = {
    
    jQuery : $,
    
    settings : {
        columns : '.column',
        widgetSelector: '.widget',
        handleSelector: '.widget-head',
        contentSelector: '.widget-content',
        
        /* If you don't want preferences to be saved change this value to
            false, otherwise change it to the name of the cookie: */
        saveToCookie: 'inettuts-widget-preferences',
        
        widgetDefault : {
            movable: true,
            removable: false,
            collapsible: true,
            editable: true,
            colorClasses : ['color-yellow', 'color-red', 'color-blue', 'color-white', 'color-orange', 'color-green']
        },
        widgetIndividual : {}
    },

    init : function () {
        this.attachStylesheet('inettuts.js.css');
        this.sortWidgets();
        this.addWidgetControls();
	this.changeBackground();
        this.makeSortable();
    },
    
    getWidgetSettings : function (id) {
        var $ = this.jQuery,
            settings = this.settings;
        return (id&&settings.widgetIndividual[id]) ? $.extend({},settings.widgetDefault,settings.widgetIndividual[id]) : settings.widgetDefault;
    },
    
     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">CLOSE</a>').mousedown(function (e) {	
                    /* STOP event bubbling */	
                     e.stopPropagation();    
                 }).click(function () {	
                     if(confirm('This widget will be removed, ok?')) { 	
                        $(this).parents(settings.widgetSelector).animate({	
                             opacity: 0    
                        },function () {	
                             /*$(this).wrap('<div/>').parent().slideUp(function () {	
                                 $(this).remove();	
                             }); 	*/
							 $(this).addClass('removed');
							iNettuts.savePreferences();						 
                         });
						//$(this).parents(settings.widgetSelector).addClass('removed'); 
                     }	
                     return false;	
                 }).appendTo($(settings.handleSelector, this));	
             }	
            
            if (thisWidgetSettings.editable) {
                $('<a href="/#" class="edit">EDIT</a>').mousedown(function (e) {
                    /* STOP event bubbling */
                    e.stopPropagation();    
                }).click(function () {
					if($(this).css('width') == '24px'){
                    $(this).css({backgroundPosition: '-66px 0', width: '55px'})
                        .parents(settings.widgetSelector)
                            .find('.edit-box').show().find('input').focus();
					if($(this).parents('.widget').attr('id') == 'egyedi'){
					$(this).parents(settings.handleSelector).siblings(settings.contentSelector).children('ul').children().each(function(){
						$(this).append('<img style="margin:0px 0px 0px 0px;  border: 0px; " class="mentes" src="img/accept.png" alt="mentés" title="mentés" /><img style="margin:0px 0px 0px 10px;  border: 0px;" class="torles" src="img/delete.png" alt="törlés" title="link törlése" />');
						if($(this).attr('publikus') == 0){
							$(this).append('<img style="margin:0px 25px 0px 10px; border: 0px;" class="lock" src="img/lock.png" alt="privát" title="privát" />');
						}else{
							$(this).append('<img style="margin:0px 25px 0px 10px; border: 0px;" class="lock" src="img/lock_unlock.png" alt="publikus" title="publikus" />');
						}
						$(this).append('<input type=text size=29 value='+$(this).children('a').text()+' class="namebox" /><input type=text size=29 value='+$(this).children('a').attr('href')+' class="linkbox" />').children('a').css('display','none');
					});
					$(this).parents(settings.handleSelector).siblings(settings.contentSelector).children('ul').append('<li class="addlink"><button onclick="addLink()">Új link</button></li>');
                    $('#egyedi img[class=torles]').each(function(){
						$(this).click(function(){ deleteLink($(this))});
					});
					$('#egyedi img[class=mentes]').each(function(){
						$(this).click(function(){ saveLink($(this))});
					});
					$('#egyedi img[class=lock]').each(function(){
						$(this).click(function(){ lockLink($(this))});
					});
					$('#egyedi input[class=namebox],#egyedi input[class=linkbox]').each(function(){
						$(this).change(function(){ $(this).parent().css('background','red');$(this).parent().attr('unsaved','true')});
					});
					}
					return false;
                //},function () {
				}else{
					if($(this).parents('.widget').attr('id') == 'egyedi'){
					var zarhato = true;
					if($('#egyedi .widget-content li[unsaved]').length > 0){
					 zarhato = false;
					 if(confirm('Vannak nem mentett linkek! Ha az ok-ot választja a nem mentett változtatások elvesznek!')) {
					  zarhato = true;
					 }
					}
					if(zarhato){
                    $(this).css({backgroundPosition: '', width: '24px'})
                        .parents(settings.widgetSelector)
                            .find('.edit-box').hide();
					$(this).parents(settings.handleSelector).siblings(settings.contentSelector).children('ul').empty();
						$.ajax({
					   type: "POST",
					   url: "action_handler.php",
					   data: "type=getlinks",
					   dataType: "json",
					   success: function(msg){
						 var links = new Array();
						 var linknev = new Array();
						 var id = new Array();
						 var publikus = new Array();
						 if(msg.links != undefined){
						 links = msg.links.split(',');
						 linknev = msg.linknev.split(',');
						 id = msg.id.split(',');
						 publikus = msg.publikus.split(',');
						 for(var i=0;i < links.length;i++){
							$('#egyedi .widget-content ul').append("<li linkid='"+id[i]+"' publikus='"+publikus[i]+"'><a href='"+links[i]+"' title='"+linknev[i]+"' target='_blank' >"+linknev[i]+"</a></li>");
						 }
						 }
						 
					   }
						});
					}
					}else{
						$(this).css({backgroundPosition: '', width: '24px'})
                        .parents(settings.widgetSelector)
                            .find('.edit-box').hide();
					}
                    return false;
					}
                }).appendTo($(settings.handleSelector,this));
                $('<div class="edit-box" style="display:none;"/>')
                   /* .append('<ul><li class="item"><label>Change the title?</label><input value="' + $('h3',this).text() + '"/></li>') */
                    .append((function(){
                        var colorList = '<li class="item"><label>Dobozszín:</label><ul class="colors">';
                        $(thisWidgetSettings.colorClasses).each(function () {
                            colorList += '<li class="' + this + '"/>';
                        });
                        return colorList + '</ul>';
                    })())
                    .append('</ul>')
                    .insertAfter($(settings.handleSelector,this));
            }
            
            if (thisWidgetSettings.collapsible) {
                $('<a href="/#" class="collapse">COLLAPSE</a>').mousedown(function (e) {
                    /* STOP event bubbling */
                    e.stopPropagation();    
                }).click(function(){
                    $(this).parents(settings.widgetSelector).toggleClass('collapsed');
                    /* Save prefs to cookie: */
                    iNettuts.savePreferences();
                    return false;    
                }).prependTo($(settings.handleSelector,this));
            }
        });
        
        $('.edit-box').each(function () {
        
            $('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]);
			
                    /* Save prefs to cookie: */
                    iNettuts.savePreferences();
                }
                return false;
                
            });
        });
        
    },
     
	changeBackground : function () {
  	  var iNettuts = this,	
            $ = this.jQuery,	
             settings = this.settings;	

	$('ul.bodycolors li').click(function () {
	
                var bodycolorStylePattern = /\bbodycolor-[\w]{1,}\b/,
                    thisWidgetBodyColorClass = $("body").attr('class').match(bodycolorStylePattern)
			
			
                if (thisWidgetBodyColorClass) {
			
                    $("body")
                        .removeClass(thisWidgetBodyColorClass[0])
                        .addClass($(this).attr('class').match(bodycolorStylePattern)[0]);
			 

                    /* Save prefs to cookie: */
                    iNettuts.savePreferences();

			

                }
                return false;
                
            });   
        
       
    },

    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 = '';
                $(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'
        }).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: 100,
            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');
                /* Save prefs to cookie: */
                iNettuts.savePreferences();
            }
        });
    },
    
    savePreferences : function () {
        var iNettuts = this,
            $ = this.jQuery,
            settings = this.settings,
            cookieString = '';
            
        if(!settings.saveToCookie) {return;}
        
        /* Assemble the cookie string */
        $(settings.columns).each(function(i){
            cookieString += (i===0) ? '' : '|';
            $(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' + ',';
                cookieString += $(this).attr('class').match(/removed/)+',';
			});
        });

	  	/* Background Color of widget (color classes) */
        	cookieString += "," + "bcolor=" + $("body").attr('class').match(/\bbodycolor-[\w]{1,}\b/);
			if($('#toc .toc-head').hasClass('collapsed')){
			 cookieString += ",collapsed";
			}else{
			 cookieString += ",not-collapsed";	
			}
			if($('#navlist .kilep').length > 0){	
				$.ajax({
				   type: "POST",
				   url: "action_handler.php",
				   data: "type=setcookie&cookie="+cookieString,
				   async:false,
				   success: function(msg){

				   }
				 });
			}else{
				$.cookie(settings.saveToCookie,cookieString,{
					expires: 10
					//path: '/'
				});
		}
    },
    
    sortWidgets : function () {
        var iNettuts = this,
            $ = this.jQuery,
            settings = this.settings;
			var cookie ="";
			if($('#navlist .kilep').length > 0){
			$.ajax({
				   type: "POST",
				   url: "action_handler.php",
				   data: "type=getcookie",
				   dataType: "json",
				   async:false,
				   success: function(msg){
					 if(msg.resp == 'true'){
						cookie = msg.cookie;
					 }else{
						cookie = $.cookie(settings.saveToCookie);
					 }
				   }
				 });
			}else if($('#user').length > 0){
			$.ajax({
				   type: "POST",
				   url: "action_handler.php",
				   data: "type=getcookie&fnev="+$('#user').attr('fnev'),
				   dataType: "json",
				   async:false,
				   success: function(msg){
					 if(msg.resp == 'true'){
						cookie = msg.cookie;
					 }else{
						cookie = $.cookie(settings.saveToCookie);
					 }
				   }
				 });
			}else{
				cookie = $.cookie(settings.saveToCookie);
			}
				 //alert(cookie);
        /* Read cookie: */
        //var cookie = $.cookie(settings.saveToCookie);
        if(!settings.saveToCookie||!cookie) {
            /* Get rid of loading gif and show columns:
            $('body').css({background:'#fbe'}); */
            $(settings.columns).css({visibility:'visible'});
            return;
        }
	
	/* background change */
	/* ATIRNI A GREENT ALTALANOSRA !!! */
	var  value = (cookie.split('bcolor=')[1]).split(',')[0];
	$("body").removeAttr("class").addClass(value);
    
	if((cookie.split('bcolor=')[1]).split(',')[1] == 'collapsed'){
		$('#toc .toc-head').addClass('collapsed');
		$('#toc .collapse').css("background-position","-38px 0");
		$('#toc .toc-content').hide();
	}else{
		$('#toc .collapse').css("background-position","-52px 0");
		$('#toc .toc-content').show();
	}
        /* For each column */
        $(settings.columns).each(function(i){
            
            var thisColumn = $(this),
                widgetData = cookie.split('|')[i].split(';');
            
            $(widgetData).each(function(){
                if(!this.length) {return;}
                var thisWidgetData = this.split(',');
				if($('#' + thisWidgetData[0]).length > 0){
                  var  clonedWidget = $('#' + thisWidgetData[0]);
                  var  colorStylePattern = /\bcolor-[\w]{1,}\b/;
                  var  thisWidgetColorClass = $(clonedWidget).attr('class').match(colorStylePattern);
               
                /* Add/Replace new colour class: */
                if (thisWidgetColorClass) {
                    $(clonedWidget).removeClass(thisWidgetColorClass[0]).addClass(thisWidgetData[1]);
                }
                
                /* Add/replace new title (Bring back reserved characters): */
                $(clonedWidget).find('h3:eq(0)').html(thisWidgetData[2].replace(/\[-PIPE-\]/g,'|').replace(/\[-COMMA-\]/g,','));
                
                /* Modify collapsed state if needed: */
                if(thisWidgetData[3]==='collapsed') {
                    /* Set CSS styles so widget is in COLLAPSED state */
                    $(clonedWidget).addClass('collapsed');
                }
				if(thisWidgetData[4]==='removed'){
					$(clonedWidget).addClass('removed');
				}
                $('#' + thisWidgetData[0]).remove();
                $(thisColumn).append(clonedWidget);
				}
            });
        });
        
        /* All done, remove loading gif and show columns: */
      
        $(settings.columns).css({visibility:'visible'});
    }
  
};

if($('#user').length > 0){
 iNettuts.settings.widgetDefault.movable = false;
 iNettuts.settings.widgetDefault.editable = false;
 iNettuts.settings.widgetDefault.collapsible = false;
}
iNettuts.init();

