var offerSliderTimer = 0;
var hasFlash = false;

try {
  var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
  if(fo) hasFlash = true;
}catch(e){
  if(navigator.mimeTypes ["application/x-shockwave-flash"] != undefined) hasFlash = true;
}

function offerSlide(next) {

	var current = $('#showInvest #offer-images img:first-child');
	if(!next) next = current.next();
	
	var next_id = $(next).attr('id');
	
	$('#showInvest ul.images-navi li a').removeClass('active');
	$('#showInvest ul.images-navi li a[data-rel=' + next_id + ']').addClass('active');

	$('#showInvest #offer-images img').each(function() {
		if($(this).attr('id') == next_id) return false;
		
		$(this).insertAfter('#showInvest #offer-images img:last-child');
	});
	
}

function validateSubscripForm() {

	var msg_data = $('#mailform').attr('data-' + 'msg').split('|');
	var error = 0;
	var msg = '';

	var email_value = $('#mailform #mailform_email').val();
	var categories_checked = $('#mailform input[name*="module_sys_dmail_category"]:checked').length;
	var disclaimer_checked = $('#mailform_disclaimer:checked').length;

	if(disclaimer_checked == 0) {
		error = 3;
		msg = msg_data[2];
	}	
	
	if(categories_checked == 0) {
		error = 2;
		msg = msg_data[1];
	}	

	if(email_value == '') {
		error = 1;
		msg = msg_data[0];
	}
	
	if(error > 0) {
		alert(msg);
		return false;
	} else {
		return true;
	}
	
	
	
}

function cloneItem(input, parent, input_clone_id, input_clone_name, label) {

	var wrapper = $('<p class="right additional-field" />');
	$(wrapper).appendTo($(parent));

	if(label) {
		lbl = $('<label for="' + input_clone_id + '">' + ($(label).text()).replace('*', '') + '</label>');
		$(lbl).appendTo($(wrapper));
	}

	var input_clone = $(input).clone();
	$(input_clone).attr('id', input_clone_id);
	$(input_clone).attr('name', input_clone_name);
	$(input_clone).val('');
	$(input_clone).removeAttr('required');
	$(input_clone).appendTo($(wrapper));

}


(function($){

	 $.fn.extend({
		customStyle : function(options) {
		  if(!$.browser.msie || ($.browser.msie&&$.browser.version>6)){
		  return this.each(function() {
				var currentSelected = $(this).find(':selected');
				$(this).after('<span class="customSelect"><span class="customSelectInner">'+currentSelected.text()+'</span></span>').css({position:'absolute', opacity:0,fontSize:$(this).next().css('font-size')});
				var selectBoxSpan = $(this).next();
				var selectBoxWidth = parseInt($(this).width()) - parseInt(selectBoxSpan.css('padding-left')) -parseInt(selectBoxSpan.css('padding-right'));
				var selectBoxSpanInner = selectBoxSpan.find(':first-child');
				selectBoxSpan.css({display:'inline-block'});
				selectBoxSpanInner.css({width:selectBoxWidth, display:'inline-block'});
				var selectBoxHeight = parseInt(selectBoxSpan.height()) + parseInt(selectBoxSpan.css('padding-top')) + parseInt(selectBoxSpan.css('padding-bottom'));
				$(this).height(selectBoxHeight).change(function(){
				selectBoxSpanInner.text($(this).find(':selected').text()).parent().addClass('changed');
				});
		  });
		  }
		}
	 });
  
})(jQuery);

$(document).ready(function(){

	if(screen.width == 1024) {
		var container_left = parseInt((1024 - parseInt($('body').width())) / 2);
		$('#container').css('left', '-' + container_left + 'px');
		$('body').css('overflow', 'auto');
		$('body').css('overflow-x', 'hidden');
	}

    $('.customSelect').customStyle();

    $('.investInfoBox a.switch').click(function() {
    
		var container = $('.investInfoBox');
        if($(container).hasClass('open')) {
            $(container).animate({marginLeft:915},'fast',function(){
                $(container).removeClass('open').addClass('close');
            });
        } else {
            $(container).animate({marginLeft:472},'fast',function(){
                $(container).removeClass('close').addClass('open');
            });
        }
        
        return false;
    });
    
	var dates = $("#date_from, #date_to").datepicker({
		dateFormat: 'dd-mm-yy',
		dayNames: ['Poniedziałek', 'Wtorek', 'Środa', 'Czwartek', 'Piątek', 'Sobota', 'Niedziela'],
		dayNamesMin: ['Po', 'Wt', 'Śr', 'Cz', 'Pi', 'So', 'N'],
		dayNamesShort: ['Pon', 'Wt', 'Śr', 'Czw', 'Pi', 'So', 'Ni'],
		firstDay: 0,
		monthNames: ['Styczeń','Luty','Marzec','Kwiecień','Maj','Czerwiec','Lipiec','Sierpień','Wrzesień','Październik','Listopad','Grudzień'],
		monthNamesShort: ['Styczeń','Luty','Marzec','Kwiecień','Maj','Czerwiec','Lipiec','Sierpień','Wrzesień','Październik','Listopad','Grudzień'],
		defaultDate: "+0",
		changeMonth: true,
		changeYear: true,		
		numberOfMonths: 1,
		prevText: 'Poprzedni',
		nextText: 'Następny',
		onSelect: function( selectedDate ) {
			var option = this.id == "date_from" ? "minDate" : "maxDate",
				instance = $( this ).data( "datepicker" ),
				date = $.datepicker.parseDate(
					instance.settings.dateFormat ||
					$.datepicker._defaults.dateFormat,
					selectedDate, instance.settings );
			dates.not( this ).datepicker( "option", option, date );
		},
    	beforeShow: function(input) {
			var maxDate = $(input).attr('data-' + 'max-date').toString();
			return {
				maxDate: maxDate
			}	
    	}
	});    
	
	$('a.callendar-ico').click(function() {
		var attr_name = 'rel';
		var elem_id = $(this).attr('data-' + attr_name);
		
		$('#' + elem_id).focus();
		
		return false;
	});

    $('a[rel=external]').click(function() {
		window.open(this.href, '_blank');
		return false;	
    });
    
    $('a.print-link').click(function() {
		window.print();
		return false;
    });

	/*
    $('a.back-link').click(function() {
		history.back();
		return false;
    });    
    */
    
    $('input[type=text][data-default-value]').each(function() {
		$(this).focusin(function() {
			if($(this).val().indexOf('--') == 0) {
				$(this).attr('data-default-value', $(this).val());
				$(this).val('');
			}
		});
			
		$(this).focusout(function() {
			if($(this).val() == '') {
				$(this).val($(this).attr('data-' + 'default-value'));
				$(this).attr('data-default-value', '');
			}
		});
    })

	if($('#showInvest ul.images-navi li').length > 1) {
	
		//var offerSliderTimer = setInterval("offerSlide()", 1000);
	
	
		$('#showInvest ul.images-navi li a').click(function() {
		
			offerSlide($('#' + $(this).attr('data-rel')));
			return false;
		
		});
	}
	
	if($('select#offers-search-type').length > 0) {
	
		if($('select#offers-search-type').val() == 0) {
		
		}
	
		if($('select#offers-search-type').val() == 3) {
			$('#apartmentsForm p.offer-search-p-storey, #apartmentsForm p.offer-search-p-rooms').css('visibility', 'hidden');
		}
	
		$('select#offers-search-type').change(function() {
			if($(this).val() == 3) 
				$('#apartmentsForm p.offer-search-p-storey, #apartmentsForm p.offer-search-p-rooms').css('visibility', 'hidden');
			else 	
				$('#apartmentsForm p.offer-search-p-storey, #apartmentsForm p.offer-search-p-rooms').css('visibility', 'visible');
		});
	}
	
	if($('ul#offer-related-news').length > 0) {
		if($('ul#offer-related-news li').length > 1) {
		
			$('ul#offer-related-news li:not(li:first-child)').hide();
			
			$('#offer-related-news-outbox a.more').attr('data-' + 'status', 'closed')
			$('#offer-related-news-outbox a.more').show();
			
			$('#offer-related-news-outbox a.more').click(function() {
				
				if($(this).attr('data-' + 'status') == 'closed') {
					$('ul#offer-related-news li:not(li:first-child)').show();
					$(this).attr('data-' + 'status', 'open');
				} else { 
					$('ul#offer-related-news li:not(li:first-child)').hide();
					$(this).attr('data-' + 'status', 'closed');
				}	
				
				return false;
			});
		
		}
	}
	
	
	if($('#center .content-box form#mailform[name=tt_address_form] p[data-rel=mailform-offer]').length > 0) {
		
		var elems = $('#center .content-box form#mailform[name=tt_address_form] p[data-rel=mailform-offer]');
		var elems_wrap = $('<div class="mailform-offer-items" />');
		$(elems).wrapAll($(elems_wrap));
		
		var elems_ctrl_label = '';
		if($('html').attr('lang').indexOf('en') != -1) 
			elems_ctrl_label = 'Investments';
		else 	
			elems_ctrl_label = 'Inwestycje';
		
		var elems_ctrl = $('<p><a class="mailform-offer-items-ctrl close" href="#">' + elems_ctrl_label + '</a></p>');
		$(elems_ctrl).find('a').click(function() {
			$('.mailform-offer-items').toggle();
			
			if($('.mailform-offer-items').is(":visible")) {
				$(this).removeClass('close');
				$(this).addClass('open');
			} else {
				$(this).removeClass('open');
				$(this).addClass('close');			
			}	
			
			return false;
		});
		$(elems_ctrl).insertBefore('.mailform-offer-items');
		$('.mailform-offer-items').hide();
	}	
	
	
	$('ul#menu li ul li:last-child').each(function() {
		$(this).addClass('last-child');
	});
	
	if($('#mailform span.field-required label').length > 0) {
		$('#mailform span.field-required label').each(function() {
			var label = '* ' + $(this).text();
			$(this).text(label);
		});
	}

	
	$('#share-page-form-box').dialog({
			autoOpen: false,
			height: 450,
			width: 600,
			title: $('#share-page-form-box form').attr('data-' + 'header')
		});
		

	$('a.share-link').click(function() {
		$('#share-page-form-box p[id^="msg_error"]').addClass('display-none');
		$('#share-page-form-box').dialog('open');
		return false;
	});	
	
	$('#share-page-form-box form').submit(function() {
	
		var fields = $(this).find('input[type=text],input[type=hidden],textarea');
		
		
		var jsonObj = []; //declare array

		for (var i = 0; i < fields.length; i++) {
			var item = {'field': $(fields[i]).attr('name'), 'required': $(fields[i]).attr('required'), 'value': $(fields[i]).val()}
			jsonObj.push(item);		
		}

		$.ajax({
			url: "index.php",
			type: "POST",
			cache: false,
			async: true,
			data: {
			eID: "share_page",
			data: jsonObj
		},
		dataType: "json",
		success: function(response) {

			$('#share-page-form-box label').removeClass('error');
			$('#share-page-form-box p[id^="msg_error"]').addClass('display-none');
			
			$.each(
				response.error_fields,
				function(intIndex, objValue){			
					$('#share-page-form-box [name="' + objValue + '"]').prev().addClass('error');
			});
		
			$('#share-page-form-box #msg_error_' + parseInt(response.error)).removeClass('display-none');
			
			if(response.error == 0) {

			}

		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			alert(XMLHttpRequest.responseText);
		}
		});
		
		return false;
		
	});
	
	if($('#offer-office-text').length > 0) {
	
		var investInfoBoxContentWraperHeight = $('.investInfoBoxContentWraper').height();
		if(investInfoBoxContentWraperHeight != 445) {
			var diff = investInfoBoxContentWraperHeight - 445;

			$('#offer-office-text-box,#offer-office-text-scroller-outbox,#offer-office-text-outbox').css('height', (190 - diff) + 'px');
			$('#offer-office-text-scroller').css('height', (139 - diff) + 'px');		
		}
	
		var difference = ($('#offer-office-text').height()+51)-$('#offer-office-text-outbox').height(); 
		var proportion = difference / ($('#offer-office-text').height()+51); 
		var handleHeight = Math.round((1-proportion)*$('#offer-office-text-outbox').height()); 
		
			$('#offer-office-text-scroller').slider({
			orientation: "vertical",
			min: 0,
			max: 100,
			value: 100,
			slide: function(event, ui) {
				var topValue = -((100-ui.value)*difference/100);
				$("#offer-office-text").css({top:topValue}); 
			},
   		    change: function(event, ui) {
				var topValue = -((100-ui.value)*difference/100);
				$('#offer-office-text').css({top:topValue});
			}			
			});	
			
		if(difference > 0) {
			$('#offer-office-text-scroller-outbox').css('display', 'block');	
		}
		
		//additional code for mousewheel 
		$("#offer-office-text-scroller-outbox,#offer-office-text-outbox").mousewheel(function(event, delta){
			var speed = 5;
			var sliderVal = $("#offer-office-text-scroller").slider("value");//read current value of the slider
			
			sliderVal += (delta*speed);//increment the current value

			$("#offer-office-text-scroller").slider("value", sliderVal);//and set the new value of the slider

			event.preventDefault();//stop any default behaviour
		});
	}
	
	if($('form.tx_powermail_pi1_form').length > 0) {
	
		$('form.tx_powermail_pi1_form').each(function() {

			if($(this).find('input[type="button"]').length > 0) {
				var buttons = $(this).find('input[type="button"]');
				buttons.each(function(index, value) {
					$(value).click(function() {
	
						var fields = $(value).attr('data-' + 'rel');
						if(fields) {
						
							var hr = $('<hr class="form-separator" /><div class="clear"></div>');
							$(hr).appendTo($(value).parent().prev());

							$.each(
								fields.split(','),
								function(i, v) {			

									var el_count = $('[name^="tx_powermail_pi1[uid' + v + '"]').length;

									var input = $('#uid' + v);
									var label = $(input).prev();
									
									var input_clone_id = $(input).attr('id') + '_' + (el_count+1);
									var input_clone_name = $(input).attr('name').replace(']', '_add_' + (el_count+1) + ']');
									
									cloneItem($(input), $(value).parent().prev(), input_clone_id, input_clone_name, label);

							});							

						} else {

							var el_count = $(value).parent().prev().find('input').length;
							var input = $(value).parent().prev().find('input').first();
							
							var input_clone_id = $(input).attr('id') + '_' + (el_count+1);
							var input_clone_name = $(input).attr('name').replace(']', '_add_' + (el_count+1) + ']');

							cloneItem($(input), $(value).parent().prev(), input_clone_id, input_clone_name);

						
						}
						
					});
				});
			}


			if($(this).find('input[type="submit"]').length > 1 && $(this).find('input.reciver').length > 0) {
			
				var reciver = $(this).find('input.reciver');
			
				$(this).find('input[type="submit"]').each(function(index, value) {

					$(value).click(function(event) {
						$(reciver).val($(value).val());
						//event.preventDefault();
					});

				});
			}
		});
	
	}
	
	
	if(hasFlash === false) {
	
		$('#bg-image embed').hide();
		var src = $('#bg-image embed').attr('data-' + 'img-replace');

		var img = $('<img />');
		$(img).attr('src', src);
		$(img).attr('alt', '');
	
		$(img).insertBefore($('#bg-image embed'));
		
	}
	
	
	
});






 

