var page_id;
var editModus=false;
var newBoxesArray = new Array();
var newBoxesMax = 2;
var newBoxSource;
var newBoxTop = false;
var boxToReplace;
var idOfCurrentlyModifiedBox;

var bgimageedit_element_id;

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

function nl2br (str, is_xhtml) {
 	var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '' : '<br>'
    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}

function zeile_hinzufuegen(inputGruppe){
	$('#boxImageAuswahl').html("<div style='color:#FFFFFF;text-align:center;'>Boxen werden geladen</div>");
	$('#boxImageAuswahl').load("/ajax.html?action=getNewBoxList&box_gruppe="+ inputGruppe + "&page_id="+ page_id);
	newBoxesMax = 2;
	loadPopupTemplate("BoxHinzufuegenPopup", { "gruppe":inputGruppe, "page_id":page_id });
}

function box_ersetzen(inputZeile){
	newBoxesMax = 1;
	loadPopupTemplate("BoxReplacePopup", { "zeile":inputZeile } );
}

function createEvenOdd(){
	$('.row .dragbox').removeClass('even').removeClass('odd');
	$('.row').each(function(){
		$(this).find('.dragbox').filter(":odd").addClass('even');
		$(this).find('.dragbox').filter(":even").addClass('odd');
	});
}
function updateSortOrder(){
	var sortorder='';
	$('.row').each(function(){
		var rowId = $(this).attr('id');
		var itemorder=$(this).sortable('toArray');
		sortorder+=rowId+'='+itemorder.toString()+'&';
	});
	$('#debug_div').load("/ajax.html?action=movedBox&"+sortorder);
}

function initInPlaceEdit(){
	$(".text_editable").editInPlace({
		callback: function(idOfEditor, enteredText){
			enteredText=nl2br(enteredText,false);
			$('#debug_div').load("/ajax.html?action=editText&element_id="+idOfEditor+"&update_value="+escape(enteredText));
			return enteredText;
		},
		field_type: "textarea",
		textarea_rows: "15",
		textarea_cols: "15",
		params: "action=editText",
		url: "/ajax.html"
	});

	$("h3 .text_editable").editInPlace({
		callback: function(idOfEditor, enteredText){
			$('#debug_div').load("/ajax.html?action=editText&element_id="+idOfEditor+"&update_value="+escape(enteredText));
			return enteredText;
		},
		bg_over: "#AAAAAA",
		field_type: "text",
		params: "action=editText",
		url: "/ajax.html"
	});
}

function neue_boxen_uebernehmen(){
	if(newBoxesArray.length<2){
		alert("Bitte wählen Sie 2 Boxen aus")
	} else {
		for(i=0;i<newBoxesArray.length;i++){
			$.get("/createShopBox.html/"+ newBoxesArray[i] + "/"+ page_id, function(data){
				newdiv = data;
				if(newBoxTop==false){
					newBoxSource.after(newdiv);
				} else {
					newBoxSource.before(newdiv);
				}
				createEvenOdd();
				updateSortOrder(1);
				activateDragBoxActions();
				initInPlaceEdit();
			});
		}
		disablePopup();

	}
}



// This method is used to replace a box
function neue_box_uebernehmen(){

	if(newBoxesArray.length != 1){
		alert("Bitte wählen Sie genau eine Box aus")
	} else {

		var oldBoxId = boxToReplace.attr("id");
		oldBoxId = oldBoxId.substring(4, oldBoxId.length);
			$.get("/replaceShopBoxWithNewShopBox.html/"+ oldBoxId + "/" + newBoxesArray[0] + "/"+ page_id + "/true", function(data){
				boxToReplace.replaceWith (data);
				activateDragBoxActions();
				initAllWidgetsNewAfterReplacingBoxes();

				// Clear selection
				newBoxesArray = new Array();

				initInPlaceEdit();
			});
		disablePopup();
	}
}
function activateDragBoxActions() {

	$('.dragbox')
	.each(function(){
		$(this).hover(function(){
			//$(this).find('h2').addClass('collapse');
			$(this).find('.configure').css('display', 'block');
		}, function(){
				$(this).find('.configure').css('display', 'none');
				//$(this).addClass('hover');
		})
		.live("touchstart", function(){
		})
		.find('h2').hover(function(){
			$(this).find('.configure').css('visibility', 'visible');
		}, function(){
			$(this).find('.configure').css('visibility', 'hidden');
		})
		.click(function(){
			$(this).siblings('.dragbox-content').toggle();
		})
		.end()
		.find('.configure').css('visibility', 'visible');
	});

}

function initAllWidgetsNewAfterReplacingBoxes () {
	// ReInit HeaderSlider
	if($("#row0 #HSslider").find(".herospaceControls").length==0){
		$("#row0 #HSslider").herospace({controlerOption:true});
	}
}

function reloadCurrentlyModifiedShopBox() {
	$.get("/getShopBox.html/" + idOfCurrentlyModifiedBox, function(data) {
		$("#box_" + idOfCurrentlyModifiedBox).html(data);
	});
}

var ok = "<div style='height: 70px; line-height: 50px; width: 950px; float: left; text-align:center;'><img src='/bundles/vodafone/images/ajax-loader.gif' /> Daten werden geladen </div>";


$(document).ready(function(){

	//ipad click
	var ua = navigator.userAgent,
    event = (ua.match(/iPad/i)) ? "touchstart" : "click";

	$(".submenu_header").live ("click", function() {
		$(this).siblings(".submenu_content").slideToggle("slow");
		$(this).parents(".dragbox").toggleClass("lowMargin");
		$(this).children(".navShowHide").toggleClass("iconHide");
		$(this).children(".navShowHide").toggleClass("iconShow");
	});


	/* Slides aktivieren */
	$('.herospaceImages > div').hide();
	$("#HSslider").herospace({controlerOption:true});

	$('.formularBox input,.formularBox textarea,.select_login_container input').focus(function() {
		if (this.value == this.defaultValue & this.value != 'Absenden') {
			this.value = '';
		}
	});

	$('.formularBox input,.formularBox textarea,.select_login_container input').blur(function() {
		if (this.value == '') {
			this.value = this.defaultValue;
		}
	});

	$('.box_job_button').click(function() {
		var jobid = $(this).attr("id").split("_")[1];
		loadPopupTemplate("JobPopup", { "edit":0, "jobid":jobid });
	});

	$('#jungeLeuteButton').click(function(){
		loadPopupTemplate("JungeLeutePopup", false);
	});

	$('#selbststaendigeButton').click(function(){
		loadPopupTemplate("SelbststaendigePopup", false);
	});


	// Tarifboxen Popup öffnen
	$('.tarifPopup').live('click', function(){
		// Gewünschte Inhaltsbox ermitteln
		var tarif_box_name = $(this).attr('rel');
		loadPopupTemplate('TarifboxPopup',  { "tarif_box_name":tarif_box_name });
	});


	$('#button_shop_online_schalten_popup').click(function() {
		loadPopupTemplate("NeuerShopTodos", false);
	});

	$('#button_shop_versionen_popup').click(function() {
		loadPopupTemplate("Versionen", {"giverevs":1 });
	});


	if(editModus==true){

		createEvenOdd();
		//$('.dragbox').find(".inactive").fadeTo('fast', 0.7);
		$(".row").addClass("editModus");
		activateDragBoxActions();


		$('.dragbox').click(function() {
	    		$(this).find('.configure').css('display', 'block');
		});

		$("#popupImages a.menu_item").live ("click", function() {
			$("a.menu_item").removeClass("active");
			$(this).addClass("active");
		});

		$("#popupImagesForBoxReplace a.menu_item").live ("click", function() {
			$("a.menu_item").removeClass("active");
			$(this).addClass("active");
		});

		$("a.boxReplaceButton").live (event, function() {
			boxToReplace = $(this).parents(".dragbox");
			var zeile = $(this).parents(".row").attr("id").split("w")[1];
			box_ersetzen(zeile);
		});

		$("a.boxReplaceButton").live ("click", function() {
			boxToReplace = $(this).parents(".dragbox");
			var zeile = $(this).parents(".row").attr("id").split("w")[1];
			box_ersetzen(zeile);
		});

		$('.row').sortable({
			connectWith: $(this),
			handle: '.move',
			cursor: 'move',
			opacity: 0.4,
			revert:true,
			start:function(event, ui){
				$(this).find(".zeile_hinzufuegen, .zeile_entfernen").css("display", "none");
			},
			stop: function(event, ui){
				$(this).find(".zeile_hinzufuegen, .zeile_entfernen").css("display", "block");
				createEvenOdd();
				$(ui.item).find('.move').click();
				updateSortOrder();
			}
		});

		$(".text_editable").editInPlace({
			callback: function(idOfEditor, enteredText){
				enteredText=nl2br(enteredText,false);
				$('#debug_div').load("/ajax.html?action=editText&element_id="+idOfEditor+"&update_value="+escape(enteredText));
				return enteredText;
			},
			field_type: "textarea",
			textarea_rows: "15",
			textarea_cols: "15",
			params: "action=editText",
			url: "/ajax.html"
		});

		$("h3 .text_editable").editInPlace({
			callback: function(idOfEditor, enteredText){
				$('#debug_div').load("/ajax.html?action=editText&element_id="+idOfEditor+"&update_value="+escape(enteredText));
				return enteredText;
			},
			bg_over: "#AAAAAA",
			field_type: "text",
			params: "action=editText",
			url: "/ajax.html"
		});

		$('.boxImageButton').live(event, function() {
			bgimageedit_element_id=$(this).attr("id");
			var sbox_id = bgimageedit_element_id.split("_")[1];
			var bgimageedit_element=$(this).parent();
			loadPopupTemplate("BoxBildAuswaehlenPopup", { "sbox_id": sbox_id, "bgimageedit_element_id": bgimageedit_element_id, "bild_auswahl_art": 1 });
		});

		$('.boxImageButton').live('click', function() {
			bgimageedit_element_id=$(this).attr("id");
			var sbox_id = bgimageedit_element_id.split("_")[1];
			var bgimageedit_element=$(this).parent();
			loadPopupTemplate("BoxBildAuswaehlenPopup", { "sbox_id": sbox_id, "bgimageedit_element_id": bgimageedit_element_id, "bild_auswahl_art": 1 });
		});

		$('a.editHardwareBox').live(event, function() {
			var sboxId = $(this).attr("id").replace ("editHardwareBoxButton_", "");
			loadPopupTemplate("HardwareboxManagementPopup", {"sboxId":sboxId } );
		});

		$('a.editHardwareBox').live('click', function() {
			var sboxId = $(this).attr("id").replace ("editHardwareBoxButton_", "");
			loadPopupTemplate("HardwareboxManagementPopup", {"sboxId":sboxId } );
		});

		$('a.editTopTenHardwareBox').live(event, function() {
			var sboxId = $(this).attr("id").replace ("editTopTenHardwareBoxButton_", "");
			loadPopupTemplate("TopTenHardwareboxManagementPopup", {"sboxId":sboxId } );
		});

		$('a.editTopTenHardwareBox').live('click', function() {
			var sboxId = $(this).attr("id").replace ("editTopTenHardwareBoxButton_", "");
			loadPopupTemplate("TopTenHardwareboxManagementPopup", {"sboxId":sboxId } );
		});

		$('a.editSliderContentBox').live('click', function() {
			var sboxId = $(this).attr("id").replace ("editContentSliderBoxButton_", "");
			loadPopupTemplate("ContentSliderBoxManagementPopup", {"sboxId":sboxId });
		});

		$('.zeile_hinzufuegen').live(event, function() {
			newBoxSource = $(this).parents(".dragbox");
			if($(this).parent().hasClass("configure_row_top")){
				newBoxTop = true;
				if(newBoxSource.hasClass("even")){
					newBoxSource = newBoxSource.prev();
				}
			} else {
				newBoxTop = false;
				if(newBoxSource.hasClass("odd")){
					newBoxSource = newBoxSource.next();
				}
			}
			newBoxesArray = new Array();
			zeile_hinzufuegen(2);
		});

		$('.zeile_hinzufuegen').live('click', function() {
			newBoxSource = $(this).parents(".dragbox");
			if($(this).parent().hasClass("configure_row_top")){
				newBoxTop = true;
				if(newBoxSource.hasClass("even")){
					newBoxSource = newBoxSource.prev();
				}
			} else {
				newBoxTop = false;
				if(newBoxSource.hasClass("odd")){
					newBoxSource = newBoxSource.next();
				}
			}
			newBoxesArray = new Array();
			zeile_hinzufuegen(2);
		});

		$('.zeile_entfernen').hover(function(){
				var id_box_1=$(this).attr("id").split("_")[1];
				if($(this).parents(".dragbox").hasClass("even")){
					var id_box_2=$(this).parents(".dragbox").prev().attr("id").split("_")[1];
				} else {
					var id_box_2=$(this).parents(".dragbox").next().attr("id").split("_")[1];
				}
				$('#box_'+id_box_1).find(".disabled_layer").stop().fadeTo('fast', 0.7);
				$('#box_'+id_box_2).find(".disabled_layer").stop().fadeTo('fast', 0.7);
			}, function(){
				var id_box_1=$(this).attr("id").split("_")[1];
				if($(this).parents(".dragbox").hasClass("even")){
					var id_box_2=$(this).parents(".dragbox").prev().attr("id").split("_")[1];
				} else {
					var id_box_2=$(this).parents(".dragbox").next().attr("id").split("_")[1];
				}
				$('#box_'+id_box_1).find(".disabled_layer").stop().fadeOut('fast');
				$('#box_'+id_box_2).find(".disabled_layer").stop().fadeOut('fast');
		});


		$('.zeile_entfernen').live(event, function() {
			var numberOfShopBoxesInPage = $("#row1 > div.dragbox").length;
			if (numberOfShopBoxesInPage > 4) {
				var answer = confirm("Soll die ausgewählte Zeile wirklich entfernt werden?");
				if (answer){
					var id_box_1=$(this).attr("id").split("_")[1];
					//$(this).parents(".dragbox").css("background-color", "#FF0000");
					if($(this).parents(".dragbox").hasClass("even")){
						var id_box_2=$(this).parents(".dragbox").prev().attr("id").split("_")[1];
					} else {
						var id_box_2=$(this).parents(".dragbox").next().attr("id").split("_")[1];
					}
					$('#box_'+id_box_1).remove();
					$('#debug_div').load("/ajax.html?action=deleteBox&box_id="+ id_box_1);
					$('#box_'+id_box_2).remove();
					$('#debug_div').load("/ajax.html?action=deleteBox&box_id="+ id_box_2);

				}
			} else {
				alert ("Boxen können nicht gelöscht werden: Es müssen sich mindestens 4 Boxen auf einer Seite befinden.");
			}
		});

		$('.zeile_entfernen').live('click', function() {
			var numberOfShopBoxesInPage = $("#row1 > div.dragbox").length;
			if (numberOfShopBoxesInPage > 4) {
				var answer = confirm("Soll die ausgewählte Zeile wirklich entfernt werden?");
				if (answer){
					var id_box_1=$(this).attr("id").split("_")[1];
					//$(this).parents(".dragbox").css("background-color", "#FF0000");
					if($(this).parents(".dragbox").hasClass("even")){
						var id_box_2=$(this).parents(".dragbox").prev().attr("id").split("_")[1];
					} else {
						var id_box_2=$(this).parents(".dragbox").next().attr("id").split("_")[1];
					}
					$('#box_'+id_box_1).remove();
					$('#debug_div').load("/ajax.html?action=deleteBox&box_id="+ id_box_1);
					$('#box_'+id_box_2).remove();
					$('#debug_div').load("/ajax.html?action=deleteBox&box_id="+ id_box_2);

				}
			} else {
				alert ("Boxen können nicht gelöscht werden: Es müssen sich mindestens 4 Boxen auf einer Seite befinden.");
			}
		});

		$('.newbox_container').live('click', function() {
			var box_id=$(this).attr("id").split("_")[2];
			found_index = newBoxesArray.indexOf(box_id);
			if(found_index!=-1){
				$('#newbox_container_'+box_id).find('.disabled_layer').stop().fadeOut();
				newBoxesArray.splice(found_index,1);
			} else {
				if(newBoxesArray.length<newBoxesMax){
					$('#newbox_container_'+box_id).find('.disabled_layer').stop().fadeTo('fast',0.7);
					newBoxesArray.push(box_id);
				}
			}
		});


		/*
		$('.box_auswahl_komplett').live('click', function() {
			var box_id = $(this).attr("id").split("_")[1];
			//alert(sbox_id);
			var sbox_id = bgimageedit_element_id.split("_");
			var geteilt = sbox_id[3];
			//alert(box_id);
			//$('#debug_div').load("/ajax.html?action=editBgImage&element_id="+bgimageedit_element_id+"&update_value="+escape(image_src));
			//			alert("/ajax.html?action=editBoxKomplett&element_id="+bgimageedit_element_id+"&update_value="+escape(sbox_id));
			$('#debug_div').load("/ajax.html?action=editBoxKomplett&element_id="+bgimageedit_element_id+"&update_value=" + escape(box_id) + "&geteilt="+geteilt, function(){
				$('#box_'+sbox_id[1]).load("/getShopBox.html/"+sbox_id[1] +"/true");
			});
			//var id_only=bgimageedit_element_id.split("_");
			//$('#box_'+ id_only[1]).find('.container').css("background-image","url("+ image_src +")");

			disablePopup();
		});*/


		/*
		$('.box_auswahl').live('click', function() {
			var id_only=$(this).attr("id").split("_");
			$('#debug_div').load("/ajax.html?action=newBox&box_id="+ id_only[1] +"&row=5");
			disablePopup();
			window.location.href=window.location.href;
		});
		*/


		/*
		$(".neueBox").click(function(){
			loadPopup(2);
		});
		*/

		/*
		$('.deleteBox').live('click', function() {
			var answer = confirm("Soll die ausgewählte Box wirklich entfernt werden?");
			if (answer){
				var id_only=$(this).attr("id").split("_");
				$('#box_'+id_only[1]).remove();
				$('#debug_div').load("/ajax.html?action=deleteBox&box_id="+ id_only[1]);
			}
		});
		*/

		//$(".deleteBox").click(function(){
		/*
		$('.deleteBox').live('click', function() {
			if(changeAktiv==false){
				changeAktiv=true
			//var answer = confirm("Soll die ausgewählte Box wirklich gelöscht werden?");
			//if (answer){
				var id_only=$(this).attr("id").split("_");
				$('#debug_div').load("/ajax.html?action=changeactiveBox&box_id="+ id_only[1]);
				//$('#box_'+id_only[1]).remove();
				if($('#box_'+id_only[1]).find(".disabled_layer").css("display")== "none"){
					//$('#box_'+id_only[1]).find(".disabled_layer").css("display", "none");
					//$('#box_'+id_only[1]).find(".disabled_layer").animate({opacity: '0.7'});
					$('#box_'+id_only[1]).find(".disabled_layer").fadeTo('slow', 0.7, function(){
						changeAktiv=false;
						$('#box_'+id_only[1]).find(".a_box_inaktiv").css("display", "none");
						$('#box_'+id_only[1]).find(".a_box_aktiv").css("display", "block");
					});
				} else {
					//$('#box_'+id_only[1]).find(".disabled_layer").css("display", "block");
					//$('#box_'+id_only[1]).find(".disabled_layer").animate({opacity: '0'});
					$('#box_'+id_only[1]).find(".disabled_layer").fadeOut('slow', function(){
						changeAktiv=false;
						$('#box_'+id_only[1]).find(".a_box_inaktiv").css("display", "block");
						$('#box_'+id_only[1]).find(".a_box_aktiv").css("display", "none");
					});
				}
			}
			//} else {
				// Do nothing
			//}
		});
	*/

		/*
		$('.datenbankZuruecksetzen').live('click', function() {
			var answer = confirm("Soll die Datenbank wirklich auf den Urzustand zurückgesetzt werden?");
			if (answer){
				$('#debug_div').load("/ajax.html?action=datenbankZuruecksetzen", function() {
  					window.location.href=window.location.href;
				});
			}

		});*/
		/*
		$('.show_box').live('click', function() {
			disablePopup();
			var id_only=$(this).attr("id").split("_");
			$('#boxTypAuswahl').load("/ajax.html?action=loadBoxTypAuswahl&box_typ="+ id_only[1]);
			loadPopup(3);
		});*/


	}

	if($('#footer').length > 0 ){
		if(document.getElementById("row3") != null){
			var footer_offset = $('#footer').offset().top-9;
			var right_column_offset = $('#row3').offset().top;
			var temp = 0;
			if(document.getElementById('idABU179175') != null){
				temp=13;
			}
			$('#row3').css("height",(footer_offset-right_column_offset+temp)+"px");
		}
	} else if($('.sitemap').length >0){
		if(document.getElementById("row3") != null){
			var footer_offset = $('.sitemap').offset().top-9;
			var right_column_offset = $('#row3').offset().top;
			var temp = 0;
			if(document.getElementById('idABU179175') != null){
				temp=13;
			}
			$('#row3').css("height",(footer_offset-right_column_offset+temp)+"px");
		}
	}

});


/* IE IndexOf Fix */
if(!Array.indexOf){
	  Array.prototype.indexOf = function(obj){
	   for(var i=0; i<this.length; i++){
	    if(this[i]==obj){
	     return i;
	    }
	   }
	   return -1;
	  }
	}

