var beitraegeStart = 10;
var portletsSaved = true;
var cookiename = null;

$(document).ready(
	function () {
		try {
//			cookiename = $('.auswahl_speichern').attr('onclick').toString().match( /\'[a-z0-9_]+\'/g )[0].replace( '\'', '' ).replace('\'', '')
		} catch( e ) {
			cookiename = "35_doorpage";
		}


		/* Minimieren- und Schließen-Button zu den Portlets hinzufügen */
//		$('.portlet h3.portlet_functions span').append(' <a title="Box bewegen" href="#"><img class="door_button" alt="" src="/images/buttons/bewegen_btn.gif"/></a>');

		/* ZU MEIN POLITIK */
		if (cookiename != "6_doorpage") {
			$('h3.portlet_functions span').prepend(' <a href="#" class="add2mein_politikde" title="zu mein.politik hinzufügen"><img class="door_button" alt="" src="/images/buttons/hinzu_btn.gif"/></a>');
		}

		/* SCHLIESSEN */
	//	$('h3.portlet_functions span').append('<a title="Box schließen" href="#" class="close_portlet"><img class="door_button" alt="" src="/images/buttons/schliessen_btn.gif"/></a>');





		/* ... */
		$('.show_remove_portlet').bind('click', showRemovePortlet ).attr('title','Diese Box schließen');
		$('#portlet_options_nojs').hide();

		/*$('#boxen_auswahl').bind('click', toggleAuswahl);*/
		$('#boxen_auswahl_schliessen').bind('click', closeAuswahl);


		/*$('#gruppenoptionen').bind('click', toggleAuswahl);*/
		$('#gruppenoptionen_schliessen').bind('click', closeAuswahl);

		$('#threadrate img').bind('mouseover', rate);



		/* lade anordnung von portlets  */
		if (cookiename != null) {

			var co = $.cookie( cookiename );
			if( co ) {
				var spalten = co.split( '&' );
				for( var i=0; i < spalten.length; i++ ) {
					var clipboard = spalten[i].split( '=' );
					var parent = $( '#spalte2' );
					if( clipboard[0] == 'spalte1[]' ) {
						parent = $( '#spalte1' );
					}
					var c = $( '#' + clipboard[1] );
					if( c ) {
						parent.append( c.clone() );
						c.remove();
					}
				}
			}

			/* lade geschlossene portlets wenn nicht mein.politik.de */
			var co = $.cookie( cookiename+"_removed" );
			if( co ) {
				var removed = co.split( '+' );
				for( var i = 0; i < removed.length; i++ ) {
					var p = $( "#" + removed[i] + " a.close_portlet" )[0];
					if( p ) {
						closePortlet.call( p, null );
					}
				}
			}
		}

		/* Funktionalität für minimieren und schließen*/
		/*$('a.min_portlet').bind('click', toggleContent);*/
		$('a.close_portlet').bind('click', closePortlet);
		$('a.add2mein_politikde').bind('click', add2meinPolitikde);

		/* Drag 'n' Drop */
		dragAndDrop();
		image_btn( '.image_button' );
	}
);

var dragAndDrop = function(e) {
	$('.portlet h3.portlet_functions').bind('mouseover', drag);
        $('div.col').css('padding-bottom','20px');
		$('div.col').Sortable(
			{
				accept: 'portlet',
				helperclass: 'sortHelper',
				activeclass : 'sortableactive',
				hoverclass : 'sortablehover',
				handle: 'h3.portlet_functions',
				tolerance: 'pointer',
				onChange : function(ser)
				{
					savePortlets( cookiename, true, true);
				},
				onStart : function()
				{
					$.iAutoscroller.start(this, document.getElementsByTagName('body'));
				},
				onStop : function()
				{
					$.iAutoscroller.stop();
				}
			}
	);
}
var RemovedPortlets = new Array();
var showRemovePortlet = function ( e ) {
	var portlet_id = $(this).attr('id').substr(0, $(this).attr('id').lastIndexOf('_'));
    var portlet = $('#'+portlet_id);

     if (portlet.html()) {
        RemovedPortlets.push({
            id:portlet_id,
            html:portlet.clone(),
            parentId:document.getElementById(portlet_id).parentNode.id
        })
		portlet.remove();
		$('img',this).attr('src', '/images/box_2.gif');
        this.title='Diese Box einblenden';
	} else {
		for(var i=0;i<RemovedPortlets.length;i++)
            if(RemovedPortlets[i].id==portlet_id){
                $('#'+RemovedPortlets[i].parentId).prepend(RemovedPortlets[i].html);
				RemovedPortlets[i] = {};
                break;
            }

		$('img',this).attr('src', '/images/box.gif');
        this.title='Diese Box schliessen';
	}
 	//dragAndDrop();
	savePortlets( cookiename, true, true);

}

var drag = function(e) {
	$(this).css('cursor', 'move');
}

var closeAuswahl = function(e) {
	$('#boxen_auswahl_menu').slideUp(400);
	$('#gruppenoptionen_menu').slideUp(400);
	return false;
}

var closePortlet = function( e ) {
	var portlet = $( this.parentNode.parentNode.parentNode );
	RemovedPortlets.push({
		id: portlet.attr('id'),
		html: portlet.clone(),
		parentId: this.parentNode.parentNode.parentNode.parentNode.id
	});
	$('#'+portlet.attr('id')+"_check").addClass('inaktiv');
	$('#'+portlet.attr('id')+"_check img").attr('src', '/images/box_2.gif');
	savePortlets( cookiename, true, true);
	portlet.remove();
	return false;
};

var add2meinPolitikde = function(e) {
	var targetContent = $(this.parentNode.parentNode.parentNode);
	$.get("/ajax/portlet.php?add2politikde="+targetContent.attr('id'), function(text) {
		alert(text);
	});

	return false;
}


function serialize(s) {

	serial = $.SortSerialize(s);
	var location = "politikde";
	/*$.get("/update_portlets.php?"+serial.hash+"&location="+location);*/
	$.get("/update_portlets.php?"+serial.hash+"&location="+location);
	$('#col1').append("/update_portlets.php?"+serial.hash+"&location="+location);
	alert("Die Anordnung der Boxen wurde gespeichert.");
	$('#boxen_auswahl_menu').slideUp(400);
	return false;
};


function savePortlets(location, cookie, message) {
	/* Drag 'n' Drop */
	dragAndDrop();
	serial = $.SortSerialize();

	if( cookiename == "6_doorpage" ) {
		$.get("/update_portlets.php?"+serial.hash+"&location="+cookiename);
	} else if( serial.hash != "" ) {

		if (cookie) {
			$.cookie( cookiename, serial.hash, {
				path: '/',
				domain: cookieDomain,
				expires: 32
			} )
			var st = ""
			for( var i = 0; i < RemovedPortlets.length; i++ )
				if( RemovedPortlets[i] )
					st += "+" + RemovedPortlets[i].id;
			$.cookie( cookiename + "_removed", st, {
				path: '/',
				domain: cookieDomain,
				expires: 32
			} );
		} else {
			$.get("/update_portlets.php?"+serial.hash+"&location="+cookiename);
		}
	}
	if( !message )
		alert("Die Anordnung der Boxen wurde gespeichert.");
	return false;
}

function meineBeitraege(e) {
	 $.get("/ajax/meine_beitraege.php?start="+beitraegeStart, function(text){
	$('#meine_beitraege .portlet_content').html(text);
	});
	beitraegeStart += 5;
};

var rate = function(e) {
	var rating = $(this).attr('class').substr(7);
	bewertung = new Array("keine Bewertung", "Schrecklich", "Schlecht", "Durchschnittlich", "Gut", "Hervorragend");
	for (i = 1; i <= rating; i++) {
		$('#threadrate img.rating_'+i).attr('src', '/forum/images/rating/rating.gif');
	}
	for (i = 5; i > rating; i--) {
		$('#threadrate img.rating_'+i).attr('src', '/forum/images/rating/no_rating.gif');
	}
	$('#threadrate_text').html(bewertung[rating])
	$('#threadrate_vote').attr('value', rating);
}

var next = new Array(1);
next["aktive_benutzer"] = 0;
next["neue_benutzer"] = 0;
next["meine_pms"] = 0;
next["meine_gruppen"] = 0;

var weiter = function(portletId) {
	next[portletId] += 1;
	$.get("/ajax/weiter.php?portlet="+portletId+"&next="+next[portletId], function(text){
		$('#'+portletId+' .portlet_content').html(text);
	});
}

var saveMin = function() {
	var minimiert = "";
	$('.portlet').each(function(i) {
		targetContent = $('.portlet_content', this);
		if (targetContent.css('display') == 'none') {
			minimiert += this.id+"|"
		}
	});
	if (minimiert.length > 0) {
		var date = new Date();
		date.setTime(date.getTime()+(365*24*60*60*1000));
		document.cookie = location+'_min='+minimiert+"; expires="+date.toGMTString();
	}
}


var image_btn = function ( a ) {
	a = $( a ) || $( this );

	if( a ) {
		for( var i = 0; i < a.length; i++ )
			image_btn.render( a[i] );
	}
}
image_btn.render = function ( a ) {
	console.log( a.tagName );
	if( a.tagName.toLowerCase() == 'a' )
		a.innerHTML = '<table class="btn"><tr><td class="btn-left"></td><td class="btn-middle" >' + a.innerHTML + '</td><td class="btn-right"></td></tr></table>';
	else if ( a.tagName.toLowerCase() == 'input' ){
		//$( a ).wrap( '<table class="btn"><tr><td class="btn-left"></td><td class="btn-middle" ><input type="' + a.type + '" id="' + a.id + '" class="' + a.class + '" value="' + a.value + '" name="' + a.name + '" /></td><td class="btn-right"></td></tr></table>' );
		//console.log( $( a ).val() );
	} else {
		a.innerHTML = '<table class="btn"><tr><td class="btn-left"></td><td class="btn-middle" >' + a.innerHTML + '</td><td class="btn-right"></td></tr></table>';
	}
}
