﻿/// <reference path="jquery-1.3.js"/>

jQuery.extend({
	mPost: function(url, data, callback, context, error) {
		if (jQuery.isFunction(data)) {
			callback = data;
			data = {};
		}

		if (context == null) {
			context = {};
		}
		
		var errorHandler = error;
		if (jQuery.isFunction(errorHandler) == false) {
			errorHandler = defaultErrorHandler;
			context.error = error;
		}
		if (error == null) {
			error = defaultErrorHandler;
		}

		return jQuery.ajax({
			type: "POST",
			url: url,
			data: data,
			success: function(response) { callback(response,context) },
			error: function(response) {
				errorHandler(response, context);
			}
		});
	}
});


function LogException(exceptionResponse) {
	var url = resolveUrl('~/PublicServices.asmx/LogAjaxExceptionText')
	$.mPost(url, { errorText: exceptionResponse.responseText, url: location.href }, function() { }, {}, function() { });
}

function defaultErrorHandler(response, context) {
	if (!context || context.error != false) {
		alert('Na serveru nastala nečekávaná chyba\r\n\r\n Technické informace:' + response.responseText.substr(0, 200));
	}
	LogException(response);
}


var wysiwigEditor = null;
(function() {
	var htmlTemplate = "\<table cellspacing='0' cellpadding='0'							 \
						class='hintNote_table' style='									 \
						position: absolute; left: {0}px; top: {1}px;'>					 \
						<tbody>															 \
							<tr class='hintNote_popup_table_row'>						 \
								<td class='hintNote_callout_cell'>						 \
									<table cellspacing='0' cellpadding='0'				 \
										class='hintNote_arrow_table'>					 \
										<tbody>											 \
											<tr class='hintNote_arrow_table_row'>		 \
												<td class='hintNote_callout_arrow_cell'> \
													<div class='hintNote_innerdiv'>		 \
														{2}								 \
													</div>								 \
												</td>									 \
											</tr>										 \
										</tbody>										 \
									</table>											 \
								</td>													 \
								<td class='hintNote_icon_cell'>							 \
									<img border='0' src='{4}' />			 \
								</td>													 \
								<td class='hintNote_error_message_cell'>				 \
									{3}													 \
								</td>													 \
								<td class='hintNote_close_button_cell'>					 \
									<div class='hintNote_innerdiv'>						 \
										<img src='{5}' /></div>			 \
								</td>													 \
							</tr>														 \
						</tbody>														 \
					</table>";


	function setupHintNote(control,options) {
		jQuery(control).focus(function() {

			if (typeof (this.hintNote) != 'undefined') {
				$(this.hintNote).remove();
			}
			var arrow = '';
			var i;
			for (i = 14; i > 0; i--) {
				arrow += '<div style=\'width:' + i + 'px\'></div>';
			}

			var position = jQuery(this).position();
			var left = Math.ceil(position.left + jQuery(this).width() + 5);
			var top = Math.ceil(position.top - 5);

			var content = options.defaultText.length == 0 ? jQuery(this).attr('hintNoteText') : options.defaultText;

			var finalContent = htmlTemplate.replace('{0}', left + options.marginLeft)
												.replace('{1}', top)
												.replace('{2}', arrow)
												.replace('{3}', content)
												.replace('{4}', getRootUrl()+'/content/images/info.gif')
												.replace('{5}', getRootUrl()+'/content/images/close2.gif');


			jQuery(this).after(finalContent);
			this.hintNote = jQuery(this).siblings('.hintNote_table');


			jQuery(this.hintNote).show();

		});

		jQuery(control).blur(function() {
			if (this.hintNote)
				jQuery(this.hintNote).hide();
		});
	}

	jQuery.fn.extend({
		hintNote: function(options) {
			var defaultOption = { defaultText: '', marginLeft: 0 }

			var opt = jQuery.extend(defaultOption, options);
			
			return this.each(function() { setupHintNote(this, opt); });
		}
	});
})();


jQuery(document).ready(function() {
	jQuery('[hintNoteText]').hintNote();
	
	$('.autocompleter input[type=\'text\']').hintNote({ defaultText: 'Zadejte čast názvu alba fotky nebo uživatele kterého hledáte', marginLeft: 80 });
});

function getRootUrl(str) {
	if (typeof (str) == 'undefined')
		str = '';


	var ret = location.href.toLowerCase()
	if(location.pathname!='/')
		ret = ret.replace(location.pathname.toLowerCase(), '');
		
	var index = ret.indexOf('?');
	
	if (index != -1)
		return ret.substring(0, index)+str;
	return ret+str;
}

function setupRatingControl() {

	$('.ratingControl').click(function(e) {
		e.preventDefault();
		//alert(e.target.innerHTML)
		var anchor = $(e.currentTarget).find('.anchor').get(0);

		if (typeof (anchor.ratingDialog) == 'undefined') {
			anchor.parameter1 = $(anchor).parents('.ratingControl').find('span').get(0).innerHTML;

			anchor.parameter2 = $(anchor).parents('.ratingControl').find('span').get(1).innerHTML;
			anchor.parameterType = $(anchor).parents('.ratingControl').find('span').get(2).innerHTML;
			var html = "<div class='ratingControlDialog'> \
				<img src='/Content/Images/EmptyStar.png' alt='1 bod' /> \
				<img src='/Content/Images/EmptyStar.png' alt='3 body'/> \
				<img src='/Content/Images/EmptyStar.png' alt='3 body'/> \
				<img src='/Content/Images/EmptyStar.png' alt='4 body'/> \
				<img src='/Content/Images/EmptyStar.png' alt='5 bodů'/> \
				<div><span class='anchor' style='text-align:center'>Zavřít</span> \
				</div>";
			$(anchor).after(html);
			anchor.ratingDialog = $(anchor).parent().find('.ratingControlDialog').get(0);

			var position = $(anchor).position();
			var left = Math.ceil(position.left + jQuery($(anchor)).width() + 5);
			var top = Math.ceil(position.top - 5);
			

			anchor.ratingDialog.style.left = left + 'px';
			anchor.ratingDialog.style.top = top + 'px';
			var images = $(anchor).parent().find('.ratingControlDialog img');
			images.click(function(ex) {

				var value = ex.target.alt.substr(0, 1);
				$.post('/PublicServices.asmx/AddRating',
				{ parameter1: anchor.parameter1,
					parameter2: anchor.parameter2,
					type: anchor.parameterType,
					value: value
				}, function() { $(anchor.ratingDialog).hide(500); }); ;
			});

			images.mouseenter(function(mouseenterEx) {
				mouseenterEx.target.src = '/Content/Images/FilledStar.png';
				$(mouseenterEx.target).prevAll('img').each(function() {
					this.src = '/Content/Images/FilledStar.png';
				})
				$(mouseenterEx.target).nextAll('img').each(function() {
					this.src = '/Content/Images/EmptyStar.png';
				})
			});

			images.mouseout(function(mouserOutEx) {
				mouserOutEx.target.src = '/Content/Images/EmptyStar.png';
			});

			$(anchor).parent().find('.ratingControlDialog .anchor').click(function() {
				$(anchor.ratingDialog).hide(500);
			});
		}
		else {
			anchor.ratingDialog.style.display = 'block';
		}
	});
}
function resolveUrl(str) {

	if (str.toString().substr(0, 1) == '~') {
		var rootUrl = getRootUrl();
		if (rootUrl.substr(rootUrl.length - 1, 1) == '/')
			return str.replace('~/', getRootUrl());
			
		return str.replace('~', getRootUrl());
	}
	return getRootUrl() + str;
}

function MakeCorners(selector, size, imageFile, applyTo) {
	return;
	$(selector).css("position", "relative");
	if (applyTo != "bottom") {
		var classTl = imageFile + 'Tl';
		$(selector).append('<div class="' + classTl + '"></div>');
		$('.' + classTl).css("position", "absolute");
		$('.' + classTl).css("top", "-3");
		$('.' + classTl).css("left", "-3");
		$('.' + classTl).css("width", size);
		$('.' + classTl).css("height", size);
		$('.' + classTl).css("background", "url(Content/Layout/" + imageFile + ".png) no-repeat top left");
	}
	if (applyTo != "bottom") {
		var classTr = imageFile + 'Tr';
		$(selector).append('<div class="' + classTr + '"></div>');
		$('.' + classTr).css("position", "absolute");
		$('.' + classTr).css("top", "-3");
		$('.' + classTr).css("right", "-3");
		$('.' + classTr).css("width", size);
		$('.' + classTr).css("height", size);
		$('.' + classTr).css("background", "url(Content/Layout/" + imageFile + ".png) no-repeat top right");
	}
	if (applyTo != "top") {
		var classBl = imageFile + 'Bl';
		$(selector).append('<div class="' + classBl + '"></div>');
		$('.' + classBl).css("position", "absolute");
		$('.' + classBl).css("bottom", "-3");
		$('.' + classBl).css("left", "-3");
		$('.' + classBl).css("width", size);
		$('.' + classBl).css("height", size);
		$('.' + classBl).css("background", "url(Content/Layout/" + imageFile + ".png) no-repeat bottom left");
	}
	if (applyTo != "top") {
		var classBr = imageFile + 'Br';
		$(selector).append('<div class="' + classBr + '"></div>');
		$('.' + classBr).css("position", "absolute");
		$('.' + classBr).css("bottom", "-3");
		$('.' + classBr).css("right", "-3");
		$('.' + classBr).css("width", size);
		$('.' + classBr).css("height", size);
		$('.' + classBr).css("background", "url(Content/Layout/" + imageFile + ".png) no-repeat bottom right");
	}
}

function DoRoundedCorners() {
	MakeCorners(".page", 24, "cornersPage", "all");
	MakeCorners("#title", 16, "cornersTitle", "all");
	MakeCorners("#menucontainer", 14, "cornersMain", "top");
	MakeCorners("#main", 14, "cornersMain", "bottom");
	//MakeCorners( "h2", 12, "cornersHeader", "all" );
	MakeCorners(".rightImage", 12, "cornersHeader", "all");
}

/********** end or rounded corners *************************/

if (typeof (WebSite) == 'undefined') {
	WebSite = {};
}

$(document).ready(function() {
	$("input[type='text'], input[type='password']").each(function() {
		this.className = 'txt';
	});

	$("input[type='submit'], input[type='button']").each(function() {
		if(this.className=='')
			this.className = 'btn';
	});
	$("input[type='button'],button").each(function() {
		this.className = 'btn';
	});
});


function checkDocumentAnonymousUserUpload() {

	if ($("select[name='folderSelect']").length == 0 || $("select[name='folderSelect']").get(0).selectedIndex==0) {
		if (!confirm('Uploadujete fotky jako nepřihlášený uživatel. Fotky budou nahrány do zvoleného alba ve které budete moci editovat pouze ze stavající IP adresy. Opravdu si přejete pokračovat?')) {
			return false;
		}
	}
	return true;
}
function initializeDocumentPicker(pickerDiv,warning) {

	var filePicker = $(pickerDiv.parentNode).find('input[type=\'file\']').get(0);
	var htmlUpload = $(pickerDiv).find('input[type=\'button\']');
	var picker = $(pickerDiv).find('object').get(0);
	var switchArchor = $(pickerDiv).find('a').get(0);
	//switchArchor.filePicker = filePicker;
	//switchArchor.pickerDiv = pickerDiv;
	//switchArchor.onclick = initializeDocumentPicker_switchArchor_click;

	if (picker != null && typeof (picker.upload) != 'undefined') {
		picker.style.display = '';
		pickerDiv.style.display = '';
		//filePicker.parentNode.parentNode.style.display = 'none';
		picker.Script = picker.Script.replace('{0}', htmlUpload.get(0).id.replace('btnUploadMultiple', '')); ;

		htmlUpload.click(function() {
			if (!checkDocumentAnonymousUserUpload())
				return;
			$('#progressDiv').show(1000);
			window.setTimeout(function() {
				picker.Upload();
			}, 1000);
		});
	}
	else {
		//filePicker.style.display = '';
		pickerDiv.style.display = 'none';
		$('#ieInstallError').show();
		$('#anonymousUploadWarning').hide();
		$('#activeXUploadPage').hide();
		
	}

}

function tryClickLink(source, anchorIndex, e) {
	var keycode;
	if (e == null) {
		if (window.event)
			keycode = window.event.keyCode;
		else if (e)
			keycode = e.which;
		else
			return true;
	}
	else {
		keycode = e.which;
	}
	if (keycode != 13)
		return true;

	var link = $(source).find('.anchor').get(anchorIndex);
	link.click();
	if (e)
		e.preventDefault();
	return false;
}

// Appends the given value to the end of this instance.

StringBuilder.prototype = {
	append: function(value) {
		if (value) {
			this.strings.push(value);
		}
	},
	clear: function() {
		this.strings.length = 1;
	},
	toString: function() {
		return this.strings.join("");
	}
};

function setSelectionRange(input, selectionStart, selectionEnd) {
	if (input.setSelectionRange) {
		input.focus();
		input.setSelectionRange(selectionStart, selectionEnd);
	}
	else if (input.createTextRange) {
		var range = input.createTextRange();
		range.collapse(true);
		range.moveEnd('character', selectionEnd);
		range.moveStart('character', selectionStart);
		range.select();
	}
}




WebSite.addEmoticon = function(text, source) {
	var ta = $(source).parents('.smileyEditor').find('textarea').get(0); //document.getElementById(textareaid);
	//var relatedFrame = document.getElementById(textareaid + 'IFrame');
	var targetEditor = ta;
	var activeSelection = document.selection;

	if (wysiwigEditor) {

		targetEditor = wysiwigEditor;
		activeSelection = wysiwigEditor.getSelection();
		//wysiwigEditor.setSelectionContent(text);
		alert(wysiwigEditor.getBody().html());
		wysiwigEditor.getBody().wrapSelection().prepend(text);

		return;
	}
	else {
		ta.getValue = function() { return this.value; }
		ta.setValue = function(val) { return this.value = val; }
		ta.getSelectionStart = function() { return this.selectionStart; }
		ta.getSelectionEnd = function() { return this.selectionEnd; }
		ta.rootElement = function() { return this; };
	}
	//compute selection start/end
	haveStartEnd = false;
	//try {
	//IE support
	if (activeSelection && $.browser.msie) {
		targetEditor.focus();
		var sel1 = activeSelection.createRange();
		var sel2 = sel1.duplicate();
		var root = targetEditor.rootElement();
		sel2.moveToElementText(root); //Opera fails here
		sel2.setEndPoint('StartToEnd', sel1);

		var endPos = targetEditor.getValue().length - sel2.text.length;
		sel2.setEndPoint('StartToStart', sel1);
		var startPos = targetEditor.getValue().length - sel2.text.length

		prefix = targetEditor.getValue().substring(0, startPos);
		var cursorFix = -1 * (prefix.split('\r').length - 1);
		haveStartEnd = true;
	}
	//} catch (e) { }

	try {

		if (!haveStartEnd &&
            (targetEditor.getSelectionStart() || targetEditor.getSelectionStart() == 0)) {
			//Mozilla/Firefox/Netscape 7+ support
			var startPos = targetEditor.getSelectionStart();

			var endPos = targetEditor.getSelectionEnd();
			var cursorFix = 0;
			haveStartEnd = true;
		}
	} catch (e) { }

	if (!haveStartEnd) {
		//unknown browser
		targetEditor.setValue(targetEditor.getValue() + text);

		//ta.focus();
		return;
	}

	//prepend space, if not already before
	if (startPos > 0) { //do not insert space if cursor at beginning
		s = targetEditor.getValue().substring(startPos, startPos - 1);
		if (s != ' ' && s != '\n' && s != '\r') text = ' ' + text;
	}

	//append space, if not already after
	//if (endPos<ta.value.length) {
	s = targetEditor.getValue().substring(endPos, endPos + 1);
	if (s != ' ' && s != '\n' && s != '\r') text = text + ' ';
	//}

	//replace selection / insert text
	targetEditor.setValue(
        targetEditor.getValue().substring(0, startPos) +
        text +
        targetEditor.getValue().substring(endPos, targetEditor.getValue().length));

	cursorPos = startPos + text.length + cursorFix;

	WebSite.setCaretToPos(targetEditor, cursorPos);
}

function getSel() {
	var w = window, d = document, gS = 'getSelection';
	return ('' + (w[gS] ? w[gS]() : d[gS] ? d[gS]() : d.selection.createRange().text)).replace(/(^\s+|\s+$)/g, '');
}


WebSite.setCaretToPos = function(input, pos){
		setSelectionRange(input, pos, pos);
}

WebSite.PagingFunction = {};

WebSite.PagingFunction.ListThubnailPhotos = function(startRecord, endRecord, callback) {
	
}

WebSite.MVCPager = function(rootId, replacedElementId) {
	this._root = $get(rootId);
	this._replacedElement = $get(replacedElementId);
	$(document).ready(createDelegate(this, this.init));
}

WebSite.MVCPager.prototype = {
	init: function() {
		$(this._root).find('a').click(createDelegate(this, this.anchor_click));
	},

	anchor_click: function(event) {
		event.preventDefault();
		
		var url = event.target.href;
		if (url.indexOf('?') != -1) {
			url = url + '&ajax=1';
		}
		else {
			url = url + '?ajax=1';
		}

		$.get(url, {}, createDelegate(this, this.anchor_click_callback));
	},

	anchor_click_callback: function(data) {
		this._replacedElement.innerHTML = data;
		//this.init();
	}
}

WebSite.pager = function(rootElementId, replacedElementId, totalRecords, pageSize, currentRecord, pagingFunction) {
	this._rootElement = $get(rootElementId);
	this._totalRecords = totalRecords;
	this._pageSize = pageSize;
	this._currentRecord = currentRecord;
	this._pagingFunction = pagingFunction;
	this._replacedElementId = replacedElementId; 
	this.init();
}

WebSite.pager.prototype = {
	init: function() {
		var startRecord = 0;
		if (this._rootElement.className == '')
			this._rootElement.className = 'pager';

		for (startRecord = 0; startRecord < this._totalRecords; startRecord += this._pageSize) {
			var liElement = document.createElement('li');
			var start = (startRecord + 1);
			var end = (Math.min(startRecord + this._pageSize, this._totalRecords));
			liElement.innerHTML = start + ' - ' + end;
			liElement.startRecord = startRecord;
			liElement.endRecord = end;
			this._rootElement.appendChild(liElement);
		}

		//resultBuilder.append();
		this._rootElement.innerHTML += '<div style=\'clear:both\'></div>';
		$(this._rootElement).find('li').click(createDelegate(this, this.pageClick))
	},

	pageClick: function(source) {
		$(this._rootElement).removeClass('selected');
		source.target.className = 'selected';
		this._pagingFunction(source.target.startRecord, this._pageSize, createDelegate(this, this.pageClick_finished));
	},

	pageClick_finished: function(data) {
		this._replacedElementId = data;
	}
}

WebSite.EmailSubscription = function(anchor, contentId, contentTypeId, registerClick) {
	this._anchor = anchor;
	this._contentId = contentId;
	this._contentTypeId = contentTypeId;
	if (registerClick) {
		$(anchor).click(createDelegate(this, this.init));
	}
	else {
		this.init();
	}
}

WebSite.EmailSubscription.prototype = {
	init: function(e) {

		var anchor = this._anchor;
		if (typeof (anchor.detailedDiv) == 'undefined') {
			var div = document.createElement('div');
			div.className = 'emailSubscription';
			div.contentId = this.contentId;

			$(div).keypress(function(e) {
				tryClickLink(this, 0, e);
			});

			div.contentTypeId = this.contentTypeId;
			anchor.parentNode.insertBefore(div, anchor);
			anchor.detailedDiv = div;
			var builder = new StringBuilder();
			builder.append('<table>');

			//builder.append('<tr><td colspan=\'2\'>Na vámi uvedený email zašleme informace při změně přízpěvku nebo reakci v diskuzi</td></tr>');
			builder.append('<tr><td>Váš&nbsp;e-mail:</td><td><input checked=\'checked\' class=\'txt\' type=\'text\' style=\'width:327px\'  name=\'txtEmailTextBox\' /></td></tr>');
			builder.append('</table>');
			builder.append('<span class=\'anchor\'>Odeslat</span><span class=\'anchor\'>Zavřít</span><div style=\'display:none\' class="ajaxuploader">Prosím počkejte</div>');
			div.innerHTML = builder.toString();
			div.inputText = $(div).find('.txt').get(0);
			$(div).find('.anchor:eq(0)').click(createDelegate(this, this.registerEmailSubscribe_send));
			$(div).find('.anchor:eq(1)').click(createDelegate(this, this.registerEmailSubscribe_cancel));

			div.ajaxuploader = $(div).find('.ajaxuploader').get(0);
			anchor.detailedDiv.inputText.value = '';
			this._anchor = anchor;
			this._div = div;

			//var position = getCursorPosition();
			//div.style.top = position.y + 'px';
			//div.style.left = position.x + 'px';


			$(div).find('.anchor').each(function() { this.detailedDiv = div; });
		}
		else {
			anchor.detailedDiv.style.display = 'block';
			anchor.detailedDiv.inputText.value = '';
		}
		if (e) {
			anchor.detailedDiv.style.top = e.pageY + 'px';
			anchor.detailedDiv.style.left = e.pageX + 'px';
		}
	},
	registerEmailSubscribe_cancel: function() {
		this._anchor.detailedDiv.style.display = 'none';
	},

	registerEmailSubscribe_send: function() {
		var parentDiv = this._anchor.detailedDiv;

		if (parentDiv.inputText.value == '')
			return;
		parentDiv.ajaxuploader.style.display = 'block';
		
		$.post('CommonService.asmx/SubscribeForNewsRegistations', { entityId: this._contentId,
			type: this._contentTypeId,
			email: parentDiv.inputText.value
		}, createDelegate(parentDiv, this.registerEmailSubscribe_send_queryEnd));
		return false;
	},

	registerEmailSubscribe_send_queryEnd: function() {
		this.style.display = 'none';
		this.ajaxuploader.style.display = 'none';
	}
}

function registerEmailSubscribe(anchor, contentId, contentTypeId) {
	var subs = new WebSite.EmailSubscription(anchor, contentId, contentTypeId);
}

WebSite.DynamicallyAddedControls = function(rootSelector, templateSelector, anchorSelector) {
	this._root = $(rootSelector);
	this._templateSelector = templateSelector;
	this._tempalteToCopy = this._root.find(templateSelector);
	this._addedIndex = 0;
	var button;
	if (anchorSelector == null) {
		button = $(this._root).find("input[type='button']");
		if (button.length == 0)
			button = $(this._root).find("a");
	}
	else {
		button = this._root.find(anchorSelector);
	}

	button.click(createDelegate(this, this.addClick));

	//alert($(this._root).find("input[type='button']").length);
}

WebSite.DynamicallyAddedControls.prototype = {
	addClick: function() {
		var name = this._tempalteToCopy.find("input:eq(0)").attr('name');
		var newName = name.substr(0, name.length - 1) + (this._root.find(this._templateSelector).length + 1);
		var tagName = this._tempalteToCopy.get(0).tagName;
		var originalHtmtl = this._tempalteToCopy.outer();

		var root = this._root;
		var html = originalHtmtl;
		var templateSelector = this._templateSelector;
		
		this._tempalteToCopy.find("input,textarea").each(function() {
			var name = $(this).attr('name');			
			var newName = name.substr(0, name.length - 1) + (root.find(templateSelector).length + 1);
			html = html.replace(name, newName);

		});

		this._root.find(this._templateSelector + ":last").after(html);

		var input = this._root.find(this._templateSelector + ":last input," + this._templateSelector + ":last textarea").each(function() {
			if (typeof (this.value) != 'undefined')
				this.value = '';
		});
	}
}

WebSite.DynamicTextboxes = function(rootDivId) {
	this._root = $get(rootDivId);
	$(this._root).find("input[type='button']").click(createDelegate(this, this.addClick));
	this._table = $(this._root).find("table");
}

WebSite.DynamicTextboxes.prototype = {
	addClick: function() {
		var name = this._table.find("input[type='text']:eq(0)").attr('name');
		var newName = name.substr(0, name.length - 1) + (this._table.find('tr').length + 1);
		
		var originalHtmtl = this._table.find('tr:eq(0)').html();

		var html = '<tr>' + originalHtmtl.replace(name, newName) + '</tr>';

		this._table.append(html);
		this._table.find("input[type='text']:last").get(0).value = '';
	}
}


WebSite.DynamicTextEditor = function(selector, saveHandler, options) {
	$(window).load(createDelegate(this, this.window_load));
	this.selector = selector;
	this._saveHandler = saveHandler;
	this._editorHTML = '<textarea></textarea>';
	this.options = options;

	this._htmlSourceResolver = null;
	if (typeof (options.htmlSourceResolver) != 'undefined') {
		this._htmlSourceResolver = options.htmlSourceResolver;
	}
	if (typeof (options.additionalHTML) != 'undefined') {
		this._additionalHTML = options.additionalHTML
	}
	$(selector).click(createDelegate(this, this.selector_click));
}

WebSite.DynamicTextEditor.prototype = {
	window_load: function() {
		$.get(getRootUrl() + '/custom/SmileyEditor', {}, createDelegate(this, this.window_load_callback));
	},

	window_load_callback: function(result) {
		this._editorHTML = result;
		
	},

	selector_click: function(e) {
		e.preventDefault();
		
		if (typeof (e.target.editorElement) == 'undefined') {
			var html = '<div class=\'dynamicTextEditor\'>            \
					<table><tr> '+this._additionalHTML+ '\
					<tr><td>' + this._editorHTML + ' </td></tr>\
					<tr><td><input type=\'button\' class=\'btn\' name=\'saveText\' value=\'Uložit\'/><input name=\'cancelSave\' class=\'btn\' type=\'button\' value=\'Zavřít\' /> \
					<tr><td style=\'display:none\' class=\'progres\'>... Ukládám ...</td></tr></table>  \
			</div>';
			$(e.target).after(html);
			var addedElement = $(e.target).next().get(0);
			e.target.editorElement = $(e.target).next().get(0);
			$(addedElement).show(500);

			var source = '';
			if (this._htmlSourceResolver)
				source = this._htmlSourceResolver(e.target);

			$(addedElement).find('textarea').get(0).value = source;

			var saveButton = $(addedElement).find('.btn[name=\'saveText\']');

			saveButton.get(0).targetElement = e.target;
			saveButton.click(createDelegate(this, this.save_click));
			
			var cancelButton = $(addedElement).find('.btn[name=\'cancelSave\']');
			cancelButton.click(function() {
				$(addedElement).find('.progres').hide();
				$(addedElement).hide(500);
			});
		}
		else {
			if (this._htmlSourceResolver){
				source = this._htmlSourceResolver(e.target);
				$(addedElement).find('textarea').get(0).value = source;
			}

			$(e.target.editorElement).show(500);
		}
	},
	save_click: function(e) {
		var element = $(e.target.targetElement.editorElement)
		var text = element.find('textarea').get(0).value;
		element.find('.progres').show();
		this._saveHandler(text, function() {

			$(e.target.targetElement.editorElement).hide(500);
			$(e.target.targetElement.editorElement).find('.progres').hide();
		}, e.target.targetElement);

	}
}

function setupSlideShow() {

}

WebSite.InlineSlideShow = function(rootElement, fullScreenElement, photoId, photoGuid, folderId, counterElement) {
	this._rootElement = rootElement;
	this._oroginalPhotoId = photoId;
	this._photoGuid = photoGuid;
	this._folderId = folderId;
	this._photoId = photoId;
	this._photos = null;
	this._timerStarted = false;
	this._lastPictureChange = null;
	this._pictureIndex = 0;
	this._tickLabel = null;
	this._counterElement = counterElement;
	if (this._counterElement) {
		this._counterElement.hide();
	}
	fullScreenElement.click(createDelegate(this, this._fullScreenElement_click));
	rootElement.click(createDelegate(this, this.rootElement_click));
}

WebSite.InlineSlideShow.prototype = {
	_fullScreenElement_click: function() {
		if ($get('header').style.display == 'none') {
			this.setupOriginalScreen();
		}
		else {
			this.setupFullScreen();
		}
	},
	setupFullScreen: function() {
		$('#header').slideUp();
		$('.page').each(function() {
			this.originalPadding = this.style.padding;
			this.style.paddingTop = 0;
			this.originalmargin = this.style.margin;
			this.style.margin = 0;
		});

		$('#main').each(function() {
			this.originalPadding = this.style.padding;
			this.style.paddingTop = 0;
			this.originalmargin = this.style.margin;
			this.style.margin = 0;
		});
	},
	setupOriginalScreen: function() {
		$('#header').slideDown();
		$('.page').each(function() {
			this.padding = this.originalPadding;
			this.margin = this.originalmargin;
		});
		$('#main').each(function() {
			this.padding = this.originalPadding;
			this.margin = this.originalmargin;
		});
		var timeLabel = $('.timeCountLabel');
		timeLabel.text('');
		this._counterElement.hide();
	},
	rootElement_click: function(e) {
		if (this._timerStarted) {
			this._timerStarted = false;
			e.target.innerHTML = e.target.originalInnerHTML;
			this.setupOriginalScreen();
		}
		else {
			this._counterElement.show();
			this.setupFullScreen();
			e.target.originalInnerHTML = e.target.innerHTML;
			e.target.innerHTML = 'Zastavit';

			var timeLabel = $('.timeCountLabel').get(0);
			if (timeLabel == null) {
				$(e.target).after('<span class=\'timeCountLabel\'></span>');
			}

			if (this._photos == null) {
				$.post(getRootUrl('/PublicServices.asmx/GetPhotoSlideShowForFolder'),
					{ photoId: this._photoId, folderId: this._folderId, photoGuid: this._photoGuid },
					createDelegate(this, this.getPhotoSlideShowForFolder_callback));
			}
			else {
				this.changePhoto();
			}

			this._timerStarted = true;
			this.startTimer();
			this._lastPictureChange = new Date();

		}
	},

	startTimer: function() {
		this._timerStarted = true;
		window.setTimeout(createDelegate(this, this.timer_tick), 1000);
	},

	timer_tick: function() {
		this.checkPhotoChange();
		if (this._timerStarted) {
			window.setTimeout(createDelegate(this, this.timer_tick), 1 - 00);
			$('.timeCountLabel').text(Math.max(this.getTimeDifference(), 0) + 'sec.');
		}

	},

	getTimeDifference: function() {
		var date = new Date();
		var diff = date.getTime() - this._lastPictureChange.getTime();
		var seconds = Math.floor(diff / 1000);

		var time = 4;
		if (this._counterElement) {
			var val = parseInt(this._counterElement.find('input').get(0).value);
			if (isNaN(val) == false && val > 0) {
				time = val;
			}
		}
		return parseInt(Math.max(val - seconds, -1));
	},
	checkPhotoChange: function() {
		var diff = this.getTimeDifference();
		if (diff < 0)
			this.changePhoto();
	},

	changePhoto: function() {
		if (this._photos == null)
			return;

		var toShow;
		var toHide = this._photos[this._pictureIndex];

		this._pictureIndex++
		if (this._pictureIndex >= this._photos.length) {
			this._pictureIndex = 0;
		}

		toShow = this._photos[this._pictureIndex];
		//alert(this._photos[this._pictureIndex].outerHTML);
		$(toHide).fadeOut(1000, function() {
			$(toShow).fadeIn(1000);
		});

		toShow.id = toHide.id;
		toHide.id = '';
		
		if (this._pictureIndex + 1 < this._photos.length) {
			var toLoad = this._photos[this._pictureIndex + 1];
			if ($(toLoad).attr('xsrc') != '') {
				toLoad.src = $(toLoad).attr('xsrc');
				
			
			}
		}

		$('.comment').text($(toShow).attr('alt'));
		$('h5:eq(0)').text($(toShow).attr('name'));
		this._lastPictureChange = new Date();
	},

	getPhotoSlideShowForFolder_callback: function(data) {
		this._photos = new Array();
		var index = 0;

		this._photos[index] = $get('imgPictureDetail');
		
		var photos = this._photos;


		$(data).find('PhotoslideShowData').each(function() {
			var path = resolveUrl($(this).children('Path').text());
			var description = $(this).children('Description').text();
			var name = $(this).children('Name').text();
			var html = '';
			if (index == 0) {
				html = '<img src=\'' + path + '\' alt=\'' + description + '\' style=\'display:none\' name=\'' + name + '\' />';

			}
			else
				html = '<img xsrc=\'' + path + '\' alt=\'' + description + '\' style=\'display:none\' name=\'' + name + '\' />';
			//alert(photos[index]);
			$(photos[index]).after(html);  //new { path: path, description: description };

			index++;
			photos[index] = $('#imgPictureDetail').siblings('img:last').get(0);
		});
		this.checkPhotoChange();
	}
}

$(window).load(function() { setupRatingControl() });
