// JavaScript Document
var wwwbase = '';
var MAG = Object.extend({}, MAG || {});

Event.observe(window, 'load', function() {
	var proview = $('current_image');
	if (proview && proview.src.toString().indexOf('nopicture.gif')==-1) {
		proview.style.cursor = "pointer";
		Event.observe(proview, 'click', function() {
			var width = 642;
			var height = 700;
			var left = (screen.width - width)/2;
			var top = (screen.height - height)/2;
			
			MAG.openWindow(proview.src, 'Preview', 'top='+top+',left='+left+',width='+width+',height='+height+',toolbar=no,menubar=no,resizable=yes,scrollbars=yes')
		});
	}
	
	
	
	if ( $('theslider') ) {
		// parameters: list element, slide step, slider mask, number of slides visible
		var slider = new MAG.ImageSlider('theslider', 78, 'slidermask', 3);
	}
	
	if ( $('send_to_friend_button') ) {
		Event.observe('send_to_friend_button', 'click', function() {
			toggle('send_to_friend');
		});
	}
	
	if ( $('credit_calc') ) {
		Event.observe('credit_calc', 'click', function() {
			show_calculator('calculator');
		});
	}
	
	if ( $('ask_the_question') ) {
		Event.observe('ask_the_question', 'click', function() {
			show_question('send_question');
		});
	}
	
	
	if ( $('fog') ) {
		$('fog').style.width = ( navigator.userAgent.indexOf ( "MSIE" ) == -1 ? document.documentElement.scrollWidth : document.body.clientWidth ) + "px";
		$('fog').style.height = ( navigator.userAgent.indexOf ( "MSIE" ) == -1 ? document.documentElement.scrollHeight : document.body.clientHeight ) + "px" ;
		Event.observe('fog', 'click', function() {
			if ( $('send_to_friend').style.display != "none" ) {
				toggle('send_to_friend');
			} else if ( $('calculator').style.display != "none" ) {
				show_calculator('calculator');	
			} else if ( $('send_question').style.display != "none" ) {
				show_question('send_question');		
			}
		});
	}
	
	if ( $('submitbutton') ) {
		Event.observe('submitbutton', 'click', function() {
			validation();
		});
	}
	
	if ( $('submitbutton2') ) {
		Event.observe('submitbutton2', 'click', function() {
			validation2();
		});
	}


	var scripttag = document.getElementsByTagName('script')[0];
	wwwbase = scripttag.src.match(/(.*)public\/js.*/)[1];
});

MAG.ImageSlider = Class.create();
MAG.ImageSlider.prototype = {
	initialize: function(sliderObject, thumbnailSize, sliderMask, visibleSlides) {
		this.slider = $(sliderObject);
		this.sliderMask = $(sliderMask);
		this.sliderLeftOffset = this.slider.style.left ? parseInt(this.slider.style.left) : 0;
		this.thumbnailSize = thumbnailSize;
		this.visibleSlides = visibleSlides;
		

		this.maskOffset = Position.cumulativeOffset(this.sliderMask);
		this.maskSize = this.sliderMask.getDimensions();
		this.sliderSize = this.slider.getDimensions();
		
		var items = this.slider.getElementsByTagName("li");
		this.firstItem = $(items[0]);
		this.lastItem = $(items[items.length - 1]);
		
		// attach link events
		var links = $A(this.slider.getElementsByTagName("a"));
		links.each(function(thelink) {
			Event.observe(thelink, 'click', function(event) {
				var img = Event.element(event);
				$('current_image').src = img.src.replace(/_small_thumb/, '_large_thumb');
				Event.stop(event);
			});
		});
		/*
		var proview = $('current_image');
		if (proview.src.toString().indexOf('nopicture.gif')==-1) {
			proview.style.cursor = "pointer";
			Event.observe(proview, 'click', function() {
				openWindow(proview.src, 'Preview', '')
			});
		}
		*/
		
		// if the total number of images is less than or equal to the number
		// of visible slides, disable the buttons on each side
		if(links.length <= this.visibleSlides)
		{
			$('next_image').addClassName('disabled').observe('click', function() { return false; });
			$('prev_image').addClassName('disabled').observe('click', function() { return false; });
		}
		else 
		{
			Event.observe('next_image', 'click', this.shownext.bind(this));
			Event.observe('prev_image', 'click', this.showprev.bind(this));
		}
	},
	
	shownext: function() {
		var lastItemOffset = Position.cumulativeOffset(this.lastItem);
		
		// HERE
		if(this.isWithinMask(lastItemOffset[0] + this.lastItem.getDimensions().width)) {
			return;
		}
		// HERE
		
		this.sliderLeftOffset -= this.thumbnailSize;
		this.slider.style.left = this.sliderLeftOffset + 'px';
		
		//new Effect.MoveBy(this.slider, 0, -this.thumbnailSize, { duration: 0.4, fps: 30 });
	},

	showprev: function() {
		var firstItemOffset = Position.cumulativeOffset(this.firstItem);
		if(this.isWithinMask(firstItemOffset[0])) {
			return;
		}
		
		
		this.sliderLeftOffset += this.thumbnailSize;
		this.slider.style.left = this.sliderLeftOffset + 'px';
	
		//new Effect.MoveBy(this.slider, 0, this.thumbnailSize, { duration: 0.4, fps: 30 });
	},
	
	isWithinMask: function(x)
	{
		var leftborder = this.maskOffset[0];
		var rightborder = this.maskOffset[0] + this.maskSize.width;
		
		return x >= leftborder && x <= rightborder;
	}
}

MAG.openWindow = function(theURL,winName,features) {
	// get the file id from the url
	var projectid = theURL.match(/\/Project([\d]+)_([\d]+)_large_thumb\.jpg/)[1];
	var fileid = theURL.match(/\/Project([\d]+)_([\d]+)_large_thumb\.jpg/)[2];
	var url = wwwbase + 'estates/imagepopup/' +  projectid + '?file_id=' + fileid;
	
	var popupWindow = window.open(url,winName,features);
	popupWindow.focus();
}

// Calculator

function show_calculator(el) {	
	if ( $(el).style.display == "none" ) {
		var Scroll = getScroll();
		var Size = getSize();
		var styletop = ( Size[1] / 2 ) + Scroll[1] ;
		$(el).style.top = styletop + "px";
		
		Effect.Appear($(el), { duration: 0.5 });
		$('fog').toggle();
		return;
	} else {
		Effect.Fade($(el), { duration: 0.5 });
		$('fog').toggle();
		return;
	}

}

function calculate(result_text){
	y = 1*$('period').value;
	l = $('interest').value/100;
	var loan = 1*parseInt($('loan').value);

	months = y*12;
	monthlyInterest = l/12;

	discontFactor = 0;
	
	for (j=1; j<=months; j++)
		discontFactor += 1/Math.pow((1+monthlyInterest),j);
	
	monthlyPayment = loan / discontFactor;
	vnoska = monthlyPayment.toFixed(2);
	
	if(isNaN(vnoska))
		vnoska = 0;
		
	$('result').innerHTML = result_text + ': ' + vnoska + ' &euro;';
	return ;
}


// Send to friend

function toggle( el ) {
  if(!$(el)) return;
	if ( $(el).style.display == "none" ) {
		
		var Scroll = getScroll();
		var Size = getSize();
		var styletop = ( Size[1] / 2 ) + Scroll[1] ;
		$(el).style.top = styletop + "px";
		
		Effect.Appear($(el), { duration: 0.5 });
		$('fog').toggle();
		return;
	} else {
		Effect.Fade($(el), { duration: 0.5 });
		$('fog').toggle();
		return;
	}
}

function validation() {
	var error = 0;
	$('sname', 'rname', 'descript').each(function(el) { 
		if ( el.value == "" ) 
			{ el.style.border = "1px solid #FF9797"; error = 1; }
			else 
			{ el.style.border = "1px solid #66809E"; } 
	});
	
	if ( $('rmail').value != "" ) {
		var regex = /^[a-zA-Z][\w\.-_]*[a-zA-Z0-9_]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;
		if ( $F('rmail').match(regex) ) {
			$('rmail').style.border = "1px solid #66809E";	
		} else {
			error = 1;
			$('rmail').style.border = "1px solid #FF9797";
		}
	} else {
		error = 1;
		$('rmail').style.border = "1px solid #FF9797";
	}
	
	if (error) return;
	
	$('submitbutton').toggle('send_to_friend');
	$('status').toggle('send_to_friend');
	var url = wwwbase + 'offers/sendtofriend';
	var pars = 'from=' + $F('sname') + '&to=' + $F('rname') + '&tomail=' + $F('rmail') + '&url=' + $F('url') + '&descript=' + $F('descript');
	var myAjax = new Ajax.Request( url, { method: 'post', parameters: pars, onComplete: sendtofriendcomplete() } );
}

function sendtofriendcomplete() {
	$('status').toggle('send_to_friend');
	$('ready').toggle('send_to_friend');
}

// Send question
function validation2() {
	var error = 0;
	$('usernames', 'phone', 'question').each(function(el) { 
		if ( el.value == "" ) 
			{ el.style.border = "1px solid #FF9797"; error = 1; }
			else 
			{ el.style.border = "1px solid #66809E"; } 
	});
	
	
	if ( $('question_email').value != "" ) {
		var regex = /^[a-zA-Z][\w\.-_]*[a-zA-Z0-9_]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;
		if ( $F('question_email').match(regex) ) {
			$('question_email').style.border = "1px solid #66809E";	
		} else {
			error = 1;
			$('question_email').style.border = "1px solid #FF9797";
		}
	} else {
		error = 1;
		$('question_email').style.border = "1px solid #FF9797";
	}
	
	
	if (error) return;
	
	$('submitbutton2').toggle('send_question');
	$('status_question').toggle('send_question');
	var url = wwwbase + 'offers/comment';
	var pars = 'username=' + $F('usernames') + '&email=' + $F('question_email') + '&phone=' + $F('phone') + '&question=' + $F('question') + '&offer=' + $F('offer');
	var myAjax = new Ajax.Request( url, { method: 'post', parameters: pars, onComplete: sendquestioncomplete() } );
}

function sendquestioncomplete() {
	//Form.reset('form_question');
	$('status_question').toggle('send_question');
	$('ready_question').toggle('send_question');
}

function show_question( el ) {
		
	if ( $(el).style.display == "none" ) {
		
		var Scroll = getScroll();
		var Size = getSize();
		var styletop = ( Size[1] / 2 ) + Scroll[1] ;
		$(el).style.top = styletop + "px";
		
		Effect.Appear($(el), { duration: 0.3 });
		$('fog').toggle();
		return;
	} else {
		Effect.Fade($(el), { duration: 0.3 });
		$('fog').toggle();
		return;
	}
}




function getScroll() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

function getSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return [ myWidth, myHeight ];
}

MAG.openEstateWindow = function(image, event)
{
	Event.stop(event);
	
	var width = 642;
	var height = 700;
	var left = (screen.width - width)/2;
	var top = (screen.height - height)/2;

	// get the file id from the url
	var fileid = image.src.match(/\/([\d]+)_medium_thumb\.jpg/)[1];
	var url = wwwbase + 'offers/imagepopupestate/' + fileid;
	
	var popupWindow = window.open(url, 'Preview', 'top='+top+',left='+left+',width='+width+',height='+height+',toolbar=no,menubar=no,resizable=yes,scrollbars=yes');
	popupWindow.focus();
}


