/**
 * Konstruktor dla klasy pomocnicznej do tworzenia urli wedlug standardow frameworka
 * @param url - url podstawowe
 * @return
 */
function UrlHelper(url) {
	this.url = url;
	this.params = new Array();
}

UrlHelper.prototype.addFilter = function(key, value) {
	//filtry musza byc przekazywane w postaci filter[key]/value
	this.params["filter[" + key + "]"] = value;
};

UrlHelper.prototype.addParam = function(key, value) {
	this.params[key] = value;
};

UrlHelper.prototype.createUrl = function() {
	var query = this.url.replace(/\/$/,"");
	for (var key in this.params) {
		query+= "/" + key + "/" + this.params[key];
	}
	
	return query;
};

//ulatwienie dla wyszukiwania po id
function $$(id) {
	return $("#" + id);
}

/**
 * Konstruktor dla kontrolera elementow typu select ulatwiajacy laczenie selectow za pomoca Ajaxa
 * @param elementId - id selecta dla ktorego jest stworzony ten kontroler
 * @param underElementsIds - tablica selectow podleglych
 * @param progressImgId - id obrazka z progresem
 * @param ajaxUrl - url do sciagania danych
 * @param idParamName - nazwa parametru do ktorego dolaczamy zaznaczone id
 */
function SelectController(elementId, underElementsIds, progressImgId, ajaxUrl, idParamName) {
	this.elementId = elementId;
	this.underElementsIds = underElementsIds;
	this.progressImgId = progressImgId;
	this.ajaxUrl = ajaxUrl;
	this.idParamName = idParamName;
	
	//konstruktor musi byc odpalony dopiero gdy caly DOM sie zbuduje
	//linkujemy do elementu dom naszego kontrollera
	$$(this.elementId).get(0).selectController = this;
	$$(this.elementId).change(function() {
        this.selectController.selectChanged();
	});
}

SelectController.prototype.selectChanged = function() {
	this.disableUnderElements();
	
	//sprawdzamy czy istnieje element ktory mialbybyc modyfikowany
	if(!$$(this.underElementsIds[0]).get(0))
		return null;
	
	var selectedId = $$(this.elementId).get(0).options[$$(this.elementId).get(0).selectedIndex].value;
    if(selectedId == -1)
    	return null;
    
    if($$(this.progressImgId).get(0))
    	$$(this.progressImgId).show();
    
    url = new UrlHelper(this.ajaxUrl);
    url.addFilter(this.idParamName, selectedId);
    //dodajemy specjalny parametr do urla
    url.addParam("select_element_id", this.elementId);
    
    $.post(url.createUrl(), {}, function(response){
    		    		   	  $$(response.target_id).get(0).selectController.loadData(response.data); 
    					   }, "json");
};

SelectController.prototype.loadData = function(data) {
	//pierwszy element z listy underElementsIds to lista do ktorej dodamy nowe dane
	selectToModify = $$(this.underElementsIds[0]).get(0);
	selectToModify.length = 0;
	var isEmpty = true;
	for (var key in data) {
		opt = document.createElement('option');
		opt.text= data[key];
		opt.value = key;
		try {
			selectToModify.add(opt,null); // standards compliant
		}catch(ex) {
			selectToModify.add(opt); // IE only
	    } 
	    isEmpty = false;
	}
	
	if(isEmpty) {
		selectToModify.length = 0;
		selectToModify.disabled = true;
	} else {
		selectToModify.disabled = false;
	}

	if($$(this.progressImgId).get(0))
	    $$(this.progressImgId).hide();
};

SelectController.prototype.disableUnderElements = function() {
	for(var i=0; i < this.underElementsIds.length; i++) {
		select = $$(this.underElementsIds[i]).get(0);
		if(!select)
			continue;
		select.length = 0;
		opt = document.createElement('option');
		opt.text = "";
		opt.value = -1;
		try {
			select.add(opt, null); // standards compliant
		}catch(ex) {
			select.add(opt); // IE only
	    } 
		select.disabled = true;
	}
};

function changeBoxDisplay(boxToHide, boxToShow) {
  $$(boxToHide).hide();
  $$(boxToShow).show();
}

/**Metoda do pokazywania popupow obrazkowych */
function popupImage(href) {

	$("body").append("<p id='imagePopupPreview'><img src='" + href + "' alt='' /></p>");
	
	//bez tego opera nie chce dzialac
	$$("imagePopupPreview")
			.css("top", "-3320px")
			.css("left", "-3320px")
			.fadeIn("fast");
	
	$("#imagePopupPreview img").load(function() {
		var wHeight = $(window).height();
		var wWidth = $(window).width();
		var scrollTop = $(window).scrollTop();
		var scrollLeft = $(window).scrollLeft();

		var width = $$("imagePopupPreview").width();
		var height = $$("imagePopupPreview").height();
		
		var top = (wHeight - height)/2;
		if(top < 0)
			top = 20;
		var left = (wWidth - width)/2;
		if(left < 0)
			left = 20;

		$$("imagePopupPreview")
			.css("top", (scrollTop + top) + "px")
			.css("left", (scrollLeft+ left) + "px");
	});	

	$$("imagePopupPreview").click(function(e){
		$$("imagePopupPreview")
			.fadeOut("fast", function() {$$("imagePopupPreview").remove();});
	});
}

/**
 * Konstruktor dla obiektu zarzadzajacego Slideshow
 * @param contenerId - id kontenera dla slideshow
 */
function SlideShowController(contenerId, options) {
	this.interval = null;	
	
	this.slidesContainer = $('#' + contenerId + ' .slides');
	
	this.active = this.slidesContainer.children('.active').first();
    if (this.active.length == 0 ) 
    	this.active = this.slidesContainer.children().last();
    
    this.iconsContainer = $('#' + contenerId + ' .slideshowIcons');
    
    //dodajemy przyciski
    this.buttonLeft = $('#' + contenerId + ' .leftArrow');
    this.buttonRight = $('#' + contenerId + ' .rightArrow');
    this.buttonsActive = true;
	this.activateButtons();
    
	this.changeSlideSpeed = options.changeSlideSpeed;
	this.slideShowInterval = options.slideShowInterval;
	
	this.start();
}

SlideShowController.prototype.getNextSlide = function(direction) {
	if(direction == 'left')
		var next = this.active.prev().length ? this.active.prev().first(): this.slidesContainer.children().last();
	else
		var next = this.active.next().length ? this.active.next().first(): this.slidesContainer.children().first();

	return next;
};

SlideShowController.prototype.switchSlide = function(direction) {
	var next = this.getNextSlide(direction);
	var slideShowWidth = this.slidesContainer.outerWidth();
	
    var nextLeft = slideShowWidth;
    var activeLeft = -slideShowWidth;
    if(direction == 'left') {
    	nextLeft = -slideShowWidth;
    	activeLeft = slideShowWidth;
    }
    
    var instance = this;
	
    this.active.css({width: slideShowWidth})
    	  .animate({left: activeLeft}, this.changeSlideSpeed);
    
    next.css({left: nextLeft, width: slideShowWidth})
    	.addClass('active')
        .animate({left: 0}, this.changeSlideSpeed, function() {
        	instance.active.removeClass('active');          
        	instance.active = next;
        	instance.changeIcon();
        	instance.buttonsActive = true;
        });
};

SlideShowController.prototype.leftButtonClicked = function() {
	this.buttonsActive = false;
	clearInterval(this.interval);
	this.interval = null;
	this.switchSlide('left');
	this.start();
};

SlideShowController.prototype.rightButtonClicked = function() {
	this.buttonsActive = false;
	clearInterval(this.interval);
	this.interval = null;
	this.switchSlide();
	this.start();
};

SlideShowController.prototype.changeIcon = function() {
	if(this.iconsContainer.children().length == 0)
		return;
	
	this.iconsContainer.children().attr("src", "/img/slideshow_icon_off.gif");
	this.iconsContainer.children().eq(this.active.index()).attr("src", "/img/slideshow_icon_on.gif");
};

SlideShowController.prototype.activateButtons = function() {
    var instance = this;
	if(this.buttonLeft.length) {
		this.buttonLeft.click(function() {
			if(instance.buttonsActive)
				instance.leftButtonClicked();
		});
	}	
	
	if(this.buttonRight.length) {
		this.buttonRight.click(function() {
			if(instance.buttonsActive)
				instance.rightButtonClicked();
		});
	}
};

SlideShowController.prototype.start = function() {
	var instance = this;
	//zapobiegamy wielokrotnemu dodaniu intervalu
	if(this.interval == null) {
		this.interval = setInterval(function(){
										instance.switchSlide();
									}, this.slideShowInterval);
	}
};


/**
 * plugin dla slideshow
 */
jQuery.fn.slideShow = function(options) {
	  settings = jQuery.extend({
		 changeSlideSpeed : 800,
		 slideShowInterval : 6000
	  }, options);

	new SlideShowController(this.first().attr('id'), settings);  
};

/**
 * Konstruktor dla obiektu odpowiadajacego z menu typu dropdown
 */
function DropDownMenu(containerId) {
	this.containerId = containerId;
	this.timeout = 500;
	this.timerId = null;
	this.dropDownMenuItem = null;
	
	var instance = this;
	$(function(){
			    $('#' + containerId + ' .menuItem').bind('mouseover', function(){instance.open(this);});
			    $('#' + containerId + ' .menuItem').bind('mouseout', function(){instance.timer();});
			  }
	);
};
DropDownMenu.prototype.open = function(element) {
   this.canceltimer();
   this.close();
   this.dropDownMenuItem = $(element).find('ul').css('display', 'block');
};
DropDownMenu.prototype.close = function(){
	if(this.dropDownMenuItem) 
		this.dropDownMenuItem.css('display', 'none');
};
DropDownMenu.prototype.timer = function(){
	var instance = this;
	this.timerId = window.setTimeout(function(){instance.close();}, this.timeout);
};
DropDownMenu.prototype.canceltimer = function() {
	if(this.timerId){
	  window.clearTimeout(this.timerId);
      timerId = null;
    }
};

/**Podpis */
var lettersArray = new Array(100);
lettersArray[0] = '&#107;';//k
lettersArray[1] = '&#x61;';//a
lettersArray[2] = 'r';
lettersArray[3] = 't';
function createSignature() {
	$$('footer').append('<p class="wdSignature">realizacja: <a href="mailto:' + createAddress() + '">yarsoft.pl</a></p>');
}
function createAddress() {
	return lettersArray[0]+'on'+lettersArray[3]+lettersArray[1]+lettersArray[0]+
		   lettersArray[3]+'&#64;'+'y'+lettersArray[1]+lettersArray[2]+'sof'+lettersArray[3]+'&#x2E;p&#108;';
}

