/* Javascript Document Ready */ 
$(document).ready(function(){
	
	
	/* Sprache 1 auswählen */
	$('#lang').tabs({ selected: 0 });
		
	/* Elemente ausblenden */
	$('[hide="true"]').css('visibility','visible').hide();
	
	/* Formulare validieren Client */
	$('form[validate="true"]').each(function(){ $(this).validate(); });
	
	$('.noError').delay(5000).fadeTo(2500,0.01,function(){$(this).slideUp();});
	
	$('#immovideo_groesse').keyup(function(){

		var preis = 25;
		if (parseInt($('#immovideo_groesse').attr('value')))
			preis = 25 + parseInt($('#immovideo_groesse').attr('value'))*2;
		
		$('#immovideo_preis_input').val(preis);
		$('#immovideo_preis_span').html(preis);	
	});
	
	
	if ($('#checkRechnung').size()>0) {
		
		var xmlDocument = $.parseXML( '<status_notification><transaction></transaction></status_notification>' );
		alert ('test');
		var xmlRequest = $.ajax({  url: "https://api.sofort.com/api/xml",  
								   processData: false,
								   type: 'POST', 
								   contentType: 'application/xml',  
								   data: xmlDocument});
								   
		xmlRequest.done(function(msg) {  alert( msg );	});
	}
	
	if ($('#ContentFlow').size()>0)
	{
		var cf = new ContentFlow('ContentFlow', {
			useAddOns: "all",
			startItem: 4,
			reflectionColor: "transparent",
			relativeItemPosition: "center",
			reflectionHeight: 0.2,
			calcCoordinates: function (item) {
				var rP = item.relativePosition;
				//var rPN = item.relativePositionNormed;
				var vI = this.conf.visibleItems*2; 
	
				var f = 1 - 1/Math.exp( Math.abs(rP)*0.75);
				var x =  item.side * vI/(vI+1)* f; 
				var y = 1;
	
				return {x: x, y: y};
        	}
		});	
		//var cf = new ContentFlow('ContentFlow', { reflectionHeight: 0, circularFlow: false } ) ;
	}
	$('#coverflip').jcoverflip();
	
	parseGet();
	// Initialize the editor.
	// Callback function can be passed and executed after full instance creation.
	$('.admineditor').ckeditor({width:600});
	$('.editor').ckeditor({toolbar:'Immo',width:600,toolbar_Immo:
	[[ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ] ,
	 [ 'Find','Replace','-','SelectAll','-','SpellChecker', 'Scayt' ] ,
	 [ 'Bold','Italic','Underline','Strike','Subscript','Superscript','-','RemoveFormat' ],'/',
	 [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote','CreateDiv','-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','BidiLtr','BidiRtl' ],
	 [ 'Link','Unlink','Anchor' ],
	 [ 'Table','HorizontalRule','Smiley','SpecialChar' ],'/',
	 [ 'Styles','Format','Font','FontSize' ],
	 [ 'TextColor','BGColor' ]
	]});
	CKFinder.setupCKEditor( null, 'ckfinder/' ) ;

	$('.lb').lightBox({
		imageLoading: 'css/img/lightbox/lightbox-ico-loading.gif',
		imageBtnClose: 'css/img/lightbox/lightbox-btn-close.gif',
		imageBtnNext: 'css/img/lightbox/lightbox-btn-next.gif',
		imageBtnPrev: 'css/img/lightbox/lightbox-btn-prev.gif'
  	});
	
	// ToolTip
	$(".tooltip").tipTip();	
	
	
	$("#immoderwoche_gallerie").cycle({ 
		fx:     'scrollHorz',
		timeout: 6000,
		delay:  -2000 				   
	 });
	
	$("#immoderwoche_gallerie").hover(function(){
		$("#immoderwoche_gallerie").cycle('pause');
	},function(){
		$("#immoderwoche_gallerie").cycle('resume');			
	});
	
	/*
	var cf = new ContentFlow('contentflow', {
		reflectionColor: "transparent",
		useAddOns: 'all',
		maxItemHeight: 120,
		reflectionHeight: 0.25
	});*/
	
	$('table.admin td').hover(function(){
		$(this).parent('tr').find('td').css('background-color','#c9c9c9');
	},function(){
		$(this).parent('tr').find('td').css('background-color','#FFF');
	});
	
	/* Inserat Titel */ 
	$('input[name="name"]').keyup(function(){
		$('#inseratname').html($(this).val());
	});
	
	/* PLZ Ort Autocompleter */
	$( "#plz_ort" ).autocomplete({
		source: function(request, response) {
				  request['land'] = $('input[name="land"]:checked').val();
   	 			  $.ajax({
      				url: "ajax/findort.php",
      				data: request,
      				dataType: "json",
      				method: "get",
      				success: function(data){
					  response(data);
					}
                  });
  				},
		select: function( event, ui ) {
			$( "#ort_loc_id" ).val(ui.item.id);
			$( ".append_ort" ).remove();
			if (ui.item.id) {
				$.get('ajax/ortdetails.php', { term: ui.item.id } , function(data) {
			 	 	$('.insert_ort').after(data);
				});
			}
		}
	});	
	
	$('input[name="land"]').change(function(){
		$( "#plz_ort" ).val('');
		$( "#ort_loc_id" ).val('');
		$( ".append_ort" ).remove();
	});	
	
	/* Uploadify */
	initUploads();
	
	/* Unterarten */
	$('.subart').hide();
	loadSubart();
	loadBezirke();
	
	$('select[name="art"]').focus(function(){
		loadSubart();
	});
	$('select[name="art"]').change(function(){
		loadSubart();
	});
	$('select[name="art"]').keyup(function(){
		loadSubart();
		loadDetails();
	});
	$('select[name="art"]').click(function(){
		loadSubart();
		loadDetails();
	});
	$('.subart').live("keyup",function(){
		loadDetails();
	});
	$('.subart').live("click",function(){
		loadDetails();
	});
	
	$('#bundesland').live("keyup",function(){
		loadBezirke();
		$('.bezirke').find('input[type="checkbox"]').attr('checked','');
	});
	$('#bundesland').live("click",function(){
		loadBezirke();
		$('.bezirke').find('input[type="checkbox"]').attr('checked','');
	});
	
	$('#select_all').live("click",function(){
		id = $('#bundesland').val();
		if (id)
		{
			$('#bezirk_from_'+id).find('input[type="checkbox"]').attr('checked','checked');	
		}
	});
	
	$('#deselect_all').live("click",function(){
		id = $('#bundesland').val();
		if (id)
		{
			$('#bezirk_from_'+id).find('input[type="checkbox"]').attr('checked','');	
		}
	});
	
	$('.append_mitarbeiter').hide();
	$('#mitarbeiter').change(function(){
		$('.append_mitarbeiter').hide();
		if ($(this).val()=='new')
			$('.append_mitarbeiter').show();	
	});
	
	$(".ort").hide();
	
	
	
	/* Formulare validieren Client */
	$('form[validate="true"]').each(function(){ $(this).validate() });

	$("#inserateditform").validate({
		rules: {
			input_title: {
				required: true
			},
			objectid: {
				required: true,
				oidCheck: true
			}
		},
		submitHandler: function(form) {
			form.submit();
		},
		success: function(label) {
			
		},
		onkeyup: false
		
	});
		
	$.validator.addMethod('oidCheck', function(obejctid) {
		var postURL = "ajax/checkoid.php";
	
		var result;
	
		$.ajax({ 
			   type: "POST", 
			   url: postURL, 
			   data: $("#inserateditform").serialize(), 
			   dataType:"html", 
			   async:false,
			   success: function(msg) 
			   { 
					if (msg == 'true')
						result = true;
					else
						result = false;     
			   } 
		 });
		 
		 return result;
		
	},'<br />Diese Objektnummer ist bereits belegt!');
	
			
	$(".immobiliePreviewStartSlider").hover(function(){
		if ($(this).find(".immobiliePreviewImageContainer").hasClass('cycle'))
		{
			$(this).find('.immobiliePreviewImageContainer').cycle('resume');	
		}
		else
		{
			$(this).find(".immobiliePreviewImageContainer").cycle({ 
				fx:     'scrollHorz',
				timeout: 3000,
				delay:  -7500 				   
			 }).addClass('cycle');
		}
	},function(){
		$(this).find('.immobiliePreviewImageContainer').cycle('pause');		
	});
	
	$('.sort').change(function(){
		
		var tmp = $get;
		if (tmp['sort'])
			delete(tmp['sort']);
		if (tmp['sortdir'])
			delete(tmp['sortdir']);
		var adress = "?item=immo&sort="+$(this).val()+"&sortdir="+$('.sortdir').val()+http_build_query(tmp);	
		window.location = adress;	
	});
	
	$('.sortdir').change(function(){
		
		var tmp = $get;
		if (tmp['sort'])
			delete(tmp['sort']);
		if (tmp['sortdir'])
			delete(tmp['sortdir']);
		var adress = "?item=immo&sort="+$('.sort').val()+"&sortdir="+$(this).val()+http_build_query(tmp);	
		window.location = adress;	
	});
	
	$( "#progressbar" ).progressbar({
			value:parseInt($("#progressbar").attr('value'))
	});
	
	$('.immobiliePreview').hover(function(){
		if ($(this).attr('edit')==0)
			$(this).css('cursor','pointer');
	},function(){
		$(this).css('cursor','default');
	});
	
	$('.immobiliePreview').click(function(){
		
		if ($(this).attr('edit')==0)
		{
			var adress = "?item=immo&id="+$(this).attr('immoid')+"&host="+$(this).attr('immohost');
			window.location = adress;
		}	
	});
	
	$('div.immobiliePageGallerieThumbImg:first').removeClass('immobiliePageGallerieThumbImgInactive')
			.addClass('immobiliePageGallerieThumbImgActive');
	$('.immobiliePageGallerieThumbImg').hover(function(){
		$('.immobiliePageGallerieThumbImgActive').addClass('immobiliePageGallerieThumbImgInactive')
			.removeClass('immobiliePageGallerieThumbImgActive');
		$(this).removeClass('immobiliePageGallerieThumbImgInactive')
			.addClass('immobiliePageGallerieThumbImgActive');
		
		$('.immobiliePageGallerieImage img').attr('src',$(this).find('img:first').attr('src'));
		if ($(this).hasClass('file'))
			$('.imagelink').attr('href',$(this).attr('src'));
		else
			$('.imagelink').attr('href',$(this).find('a:first').attr('href'));
	});
	
	$('.buyitem').click(function(){
		updateBuyItems();
	});
	
	$('.buyitem').change(function(){
		updateBuyItems();
	});
	
	$('.show_img').hide();
	$('.show_map').click(function(){
		$('.immobiliePageMaps').show();
		$('.immobiliePageGallerie').hide();
		$('.immobiliePageVideo').hide();
		$('.show_img').show();
		$('.show_video').show();
		$(this).hide();	
	});
	
	$('.show_img').click(function(){
		$('.immobiliePageGallerie').show();
		$('.immobiliePageMaps').hide();
		$('.immobiliePageVideo').hide();
		$('.show_video').show();
		$('.show_map').show();
		$(this).hide();	
	});
	
	$('.show_video').click(function(){
		$('.immobiliePageGallerie').hide();
		$('.immobiliePageMaps').hide();
		$('.immobiliePageVideo').show();
		$('.show_img').show();
		$('.show_map').show();
		$(this).hide();	
	});
	
	$('.img-select').live('hover',function(){
	
		$(this).removeClass('ui-state-default');
		$(this).addClass('ui-state-hover');
		
	});
	$('.img-select').live('mouseout',function(){
		
		$(this).removeClass('ui-state-hover');
		$(this).addClass('ui-state-default');
		
	});
	
	$('.img-select').live('click',function(){
	
		$('.img-select').removeClass('ui-state-active');
		$('.img-select').addClass('ui-state-default');
		
		$(this).removeClass('ui-state-default');
		$(this).addClass('ui-state-active');
		
		$('#image').attr('value',$(this).attr('target'));
		$('#savepreviewimg').show();
	});	
	
	/* Activate Inactive Elements */
	$('.inactive').each(function(){
		if ($(this).attr('value'))
		{
			$(this).removeClass('inactive');  
	  		$(this).addClass('active');  
		}
		else
			$(this).attr('value',$(this).attr('default'));
	});

	$('.inactive').focus(function(){  
	  $(this).removeClass('inactive');  
	  $(this).addClass('active');
	  
	  val = $(this).attr('value');
	  def = $(this).attr('default');
	  if (def && (val.replace('\r\n','') == def.replace('\r\n','')))
		 $(this).attr('value','');   
	});
  
	$('.active').live('focusout',function(){
	  if ( ($(this).val()==$(this).attr('default')) || ($(this).val()=='') ) 
	  {
		$(this).removeClass('active');
		$(this).addClass('inactive');
		$(this).attr('value',$(this).attr('default'));  
	  }
	});
	
	/* Hide Adminbuttons */
	$('.adminbuttons').hide();
	
	/* ON Hover Show Adminbuttons */
	$('.adminbuttons').parent('div').hover(function(){$(this).children('.adminbuttons').show()},
								function(){$(this).children('.adminbuttons').hide()});
	
	ShowFormElement($('#typ').val());
	ShowChildElement();			
	extendSelection();
	
});

$(window).load(    function() {        
	// weave your magic here.    
	//$('.flow').wait(1000).css('visibility','visible');
	$('#immoderwoche_gallerie').css('visibility','visible');
});

function updateBuyItems()
{
	if ($('#border').is(':checked')) 
		$('.immobiliePreview').addClass('buyborder');	
	else
		$('.immobiliePreview').removeClass('buyborder');
	
	if ($('#bgcolor').is(':checked'))
		$('.immobiliePreview').addClass('buybgcolor');	
	else
		$('.immobiliePreview').removeClass('buybgcolor');	
		
	if ($('#immosms').is(':checked'))
	{
		$('.mobil').removeClass('mobil2');
		$('.mobilalert').hide();
		$('.mobilmsg').show();
	}
	else
	{
		$('.mobil').addClass('mobil2');	
		$('.mobilalert').show();
		$('.mobilmsg').hide();
		
	}
	
	if ($('#immoderwoche').is(':checked'))
	{
		$('.woche').find('.activeimmo').show();
		$('.woche').find('.activeimmo').next('img').hide();
	}
	else
	{
		$('.woche').find('.activeimmo').hide();
		$('.woche').find('.activeimmo').next('img').show();
	}
	
	if ($('#topranking').is(':checked'))
	{
		$('.ranking').find('.activeimmo').show();
		$('.ranking').find('.activeimmo').next().next('div').hide();
	}
	else
	{
		r = $('.ranking').find('.activeimmo').hide();
		$('.ranking').find('.activeimmo').next().next('div').show();
	}
}

function ShowFormElement(elem)
{
	$("div.artikelname").hide();
	$("div.artikeltext").hide();
	$("div#artikellink").hide();
	$("div#artikeltarget").hide();
	$("div.artikelnavname").hide();
	$("div#artikelstart").hide()
	$("div#artikeldatum").hide();
	$("div#artikelfrontpage").hide();
	$("div.artikelpretext").hide();
	$("div#artikelsptyp").hide();
	
	switch (parseInt(elem)) {
		case 0: $("div.artikeltext").show();
				$("div#artikelfrontpage").show();
				$("div.artikelnavname").show();
				$("div.artikelname").show();
				$("div#artikeltarget").show();
				$("div#artikelposition").show();
				$("div#artikelsptyp").show();
				break;
		case 1:	$("div.artikeltext").show();
				$("div.artikelpretext").show();
				$("div#artikelfrontpage").show();
				$("div#artikelposition").show();
				$("div.artikelnavname").show();
				$("div.artikelname").show();
				$("div#artikeltarget").show();
				break;
		case 2:	$("div.artikelnavname").show();
				$("div#artikelposition").show();
				break;
		case 3:	break;
		case 4: $("div.artikelnavname").show();
				$("div#artikellink").show();
				$("div#artikeltarget").show();
				$("div#artikelposition").show();
				break;
		case 5:	$("div#artikelfrontpage").show();
				$("div.artikelpretext").show();
				$("div#artikelposition").show();
				$("div.artikelnavname").show();
				$("div.artikelname").show();
				$("div.artikeltext").show();
				$("div#artikeltarget").show();
				break;
		case 6:	$("div#artikelfrontpage").show();
				$("div#artikelposition").show();
				$("div.artikelpretext").show();
				$("div.artikelnavname").show();
				$("div#artikeldatum").show();
				$("div#artikelstart").show();
				$("div.artikelname").show();
				$("div.artikeltext").show();
				$("div#artikeltarget").show();
				break;
		case 7: $("div.artikelnavname").show();
				$("div#artikeltarget").show();
				$("div#artikelposition").show();
				break;
	}
	
}

function ShowChildElement()
{
	$(".pos_select").hide();
	$("#pos_"+$('#position').val()).show();	
}

function OpenMenuElement(elem)
{	
	$('#menu_'+elem+'>child').show();
	$('[parent="'+elem+'"]').parent('div.item').show();
}

function extendSelection()
{
	$(".unterarten").hide().css('visibility','hidden');
	$('#'+$("#immobilie").val()).show().css('visibility','visible');
}

function loadDetails()
{
	var art = $('select[name="art"]').val();
	var subart = $('select[name="subart_'+art+'"]').val();
	
	if (!subart)
		subart = art;
		
	$('.append_detail').remove();
	
	$.get('ajax/appenddetails.php', { art: subart, id: $('#id').val() } , function(data) {
		$('.insert_detail').after(data);
	});
}

function loadSubart()
{
	var art = $('select[name="art"]').val();
	
	$('.subart').hide();
	$('[name="subart_' + art + '"]').show();	
}

function extendOrte()
{
	$(".ort").hide();
	if ($('#bundesland').val()>0)
		$('#div_all').show();
	$("#ort_s"+$('#bundesland').val()).show();	
}

function loadBezirke()
{
	id = $('#bundesland').val();
	
	if (id!=0)
	{
		$('.bezirke').hide();
		$('#bezirk_from_'+id).show();
		$('#select_all').show();
		$('#deselect_all').show();	
	}
	else
	{
		$('.bezirke').hide();
		$('#select_all').hide();
		$('#deselect_all').hide();
	}
}

function http_build_query(parameters){ 
	var qs = ""; 
	for(var key in parameters) { 
	  var value = parameters[key]; 
	  qs += encodeURIComponent(key) + "=" + encodeURIComponent(value) + "&"; 
	} 
	if (qs.length > 0){ 
	  qs = qs.substring(0, qs.length-1); //chop off last "&"  
	} 
	return "&"+qs; 
} 

function parseGet() { 
    var s = window.location.search.substring(1).split('&'); 
    if(!s.length) return; 
    window.$get = {}; 
    for(var i  = 0; i < s.length; i++) { 
        var parts = s[i].split('='); 
        window.$get[unescape(parts[0])] = unescape(parts[1]); 
    } 
}

function deleteFile(com,file,id)
{
	var adress = "?item=immo&action=deletefile&format="+com+"&id="+id+"&file="+file;
	var answer = confirm('Wollen Sie dieses Element wirklich entfernen?');
	if (answer)
		window.location = adress;
}
