/*
Copyright (c) 2011 Jason Palmer, http://www.jason-palmer.com/

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
jQuery.fn.DefaultValue = function(text){	
    return this.each(function(){
		//Store reference to input field
		var $input_obj = jQuery(this);

		//See if text is supplied or contained in label property
		var default_val = text || $input_obj.attr("label");

		//Make sure we're dealing with text-based form fields
		switch(this.type){
			case 'text':
			case 'password':
			case 'textarea':
				break;
			default:
				return;
		}

		//Set value initially if none are specified
        if($input_obj.val() =='') {
			$input_obj.val(default_val);
		} else {
			//Other value exists - ignore
			return;
		}

		//Remove values on focus
		$input_obj.bind('focus', function() {
			if($input_obj.val() ==default_val || $input_obj.val() =='')
				$input_obj.val('');
		});

		//Place values back on blur
		$input_obj.bind('blur',function() {
			if($input_obj.val() == default_val || $input_obj.val() == '')
				$input_obj.val(default_val);
		});

		//Capture parent form submission
		//Remove field values that are still default
		$input_obj.parents("form").each(function() {
			//Bind parent form submit
			jQuery(this).bind('submit',function() {
				if($input_obj.val() == default_val && jQuery.fn.DefaultValue.settings.clear_defaults_on_submit == true) {
					$input_obj.val('');
				}
			});
		});
    });
};
jQuery.fn.DefaultValue.settings = {
	'clear_defaults_on_submit':true
}

/*! 
 * a-tools 1.5.2
 * 
 * Copyright (c) 2009 Andrey Kramarev(andrey.kramarev[at]ampparit.com), Ampparit Inc. (www.ampparit.com)
 * Licensed under the MIT license.
 * http://www.ampparit.fi/a-tools/license.txt
 *
 * Basic usage:
 
    <textarea></textarea>
    <input type="text" />

    // Get current selection
    var sel = $("textarea").getSelection()
    
    // Replace current selection
    $("input").replaceSelection("foo");

    // Count characters
    alert($("textarea").countCharacters());

    // Set max length without callback function
    $("textarea").setMaxLength(7);

    // Set max length with callback function which will be called when limit is exceeded
    $("textarea").setMaxLength(10, function() {
        alert("hello")
    });

    // Removing limit:
    $("textarea").setMaxLength(-1);
    
    // Insert text at current caret position
    $("#textarea").insertAtCaretPos("hello");
    
    // Set caret position (1 = beginning, -1 = end)
    $("#textArea").setCaretPos(10);
    
    // Set Selection
    $("#textArea").setSelection(10,15);

 */
var caretPositionAmp = new Array();
function init() {
    if(navigator.appName == "Microsoft Internet Explorer") {
        obj = document.getElementsByTagName('TEXTAREA');
        var input;
        var i = 0;
        for (var i = 0; i < obj.length; i++) {
            input = obj[i];
            caretPositionAmp[i] = input.value.length;
            input.onmouseup = function() { // for IE because it loses caret position when focus changed
                input = document.activeElement;
                for (var i = 0; i < obj.length; i++) {
                    if (obj[i] == input) {
                        break;
                    }
                }
                input.focus();
                var s = document.selection.createRange();
                var re = input.createTextRange();
                var rc = re.duplicate();
                re.moveToBookmark(s.getBookmark());
                rc.setEndPoint("EndToStart", re);
                caretPositionAmp[i] = rc.text.length;
            }
            input.onkeyup = function() {
                input = document.activeElement;
                for (var i = 0; i < obj.length; i++) {
                    if (obj[i] == input) {
                        break;
                    }
                }
                input.focus();
                var s = document.selection.createRange();
                var re = input.createTextRange();
                var rc = re.duplicate();
                re.moveToBookmark(s.getBookmark());
                rc.setEndPoint("EndToStart", re);
                caretPositionAmp[i] = rc.text.length;
            }
        }
    }
}
window.onload = init;

jQuery.fn.extend({
    getSelection: function() {  // function for getting selection, and position of the selected text
        var input = this.jquery ? this[0] : this;
        var start;
        var end;
        var part;
        var number = 0;
        input.onmousedown = function() { // for IE 
            if (document.selection && typeof(input.selectionStart) != "number") {
                document.selection.empty();
            } else {
                window.getSelection().removeAllRanges();
            }
        }
        if (document.selection) {
            // part for IE and Opera
            var s = document.selection.createRange();
            var minus = 0;
            var position = 0;
            var minusEnd = 0;
            var re;
            var rc;
            var obj = document.getElementsByTagName('TEXTAREA');
            var pos = 0;
            for (pos; pos < obj.length; pos++) {
                if (obj[pos] == input) {
                    break;
                }
            }
            if (input.value.match(/\n/g) != null) {
                    number = input.value.match(/\n/g).length;// number of EOL simbols
            }
            if (s.text) {
                part = s.text;
                // OPERA support
                if (typeof(input.selectionStart) == "number") {
                    start = input.selectionStart;
                    end = input.selectionEnd;
                    // return null if the selected text not from the needed area
                    if (start == end) {
                        return { start: start, end: end, text: s.text, length: end - start };
                    }
                } else {
                    // IE support
                    re = input.createTextRange();
                    rc = re.duplicate();
                    firstRe = re.text;
                    re.moveToBookmark(s.getBookmark());
                    secondRe = re.text;
                    rc.setEndPoint("EndToStart", re);
                    // return null if the selectyed text not from the needed area
                    if (firstRe == secondRe && firstRe != s.text || rc.text.length > firstRe.length) {
                        return { start: caretPositionAmp[pos], end: caretPositionAmp[pos], text: "", length: 0 };
                    }
                    start = rc.text.length; 
                    end = rc.text.length + s.text.length;
                }
                // remove all EOL to have the same start and end positons as in MOZILLA
                if (number > 0) {
                    for (var i = 0; i <= number; i++) {
                        var w = input.value.indexOf("\n", position);
                        if (w != -1 && w < start) {
                            position = w + 1;
                            minus++;
                            minusEnd = minus;
                        } else if (w != -1 && w >= start && w <= end) {
                            if (w == start + 1) {
                                minus--;
                                minusEnd--;
                                position = w + 1;
                                continue;
                            }
                            position = w + 1;
                            minusEnd++;
                        } else {
                            i = number;
                        }
                    }
                }
                if (s.text.indexOf("\n", 0) == 1) {
                    minusEnd = minusEnd + 2;
                }
                start = start - minus;
                end = end - minusEnd;
                
                return { start: start, end: end, text: s.text, length: end - start };
            }
            input.focus ();
            if (typeof(input.selectionStart) == "number") {
                start = input.selectionStart;
            } else {
                s = document.selection.createRange();
                re = input.createTextRange();
                rc = re.duplicate();
                re.moveToBookmark(s.getBookmark());
                rc.setEndPoint("EndToStart", re);
                start = rc.text.length;
            }
            if (number > 0) {
                for (var i = 0; i <= number; i++) {
                    var w = input.value.indexOf("\n", position);
                    if (w != -1 && w < start) {
                        position = w + 1;
                        minus++;
                    } else {
                        i = number;
                    }
                }
            }
            start = start - minus;
            if (start == 0 && typeof(input.selectionStart) != "number") {
                start = caretPositionAmp[pos];
                end = caretPositionAmp[pos];
            }
            return { start: start, end: start, text: s.text, length: 0 };
        } else if (typeof(input.selectionStart) == "number" ) {
            start = input.selectionStart;
            end = input.selectionEnd;
            part = input.value.substring(input.selectionStart, input.selectionEnd);
            return { start: start, end: end, text: part, length: end - start };
        } else { return { start: undefined, end: undefined, text: undefined, length: undefined }; }
    },

    // function for the replacement of the selected text
    replaceSelection: function(inputStr) {
        var input = this.jquery ? this[0] : this; 
        //part for IE and Opera
        var start;
        var end;
        var position = 0;
        var rc;
        var re;
        var number = 0;
        var minus = 0;
        var mozScrollFix = ( input.scrollTop == undefined ) ? 0 : input.scrollTop;
        var obj = document.getElementsByTagName('TEXTAREA');
        var pos = 0;
        for (pos; pos < obj.length; pos++) {
            if (obj[pos] == input) {
                break;
            }
        }
        if (document.selection && typeof(input.selectionStart) != "number") {
            var s = document.selection.createRange();
            
            // IE support
            if (typeof(input.selectionStart) != "number") { // return null if the selected text not from the needed area
                var firstRe;
                var secondRe;
                re = input.createTextRange();
                rc = re.duplicate();
                firstRe = re.text;
                re.moveToBookmark(s.getBookmark());
                secondRe = re.text;
                try {
                    rc.setEndPoint("EndToStart", re);
                }
                catch(err) {
                    return this;
                }
                if (firstRe == secondRe && firstRe != s.text || rc.text.length > firstRe.length) {
                    return this;
                }
            }
            if (s.text) {
                part = s.text;
                if (input.value.match(/\n/g) != null) {
                    number = input.value.match(/\n/g).length;// number of EOL simbols
                }
                // IE support
                start = rc.text.length; 
                // remove all EOL to have the same start and end positons as in MOZILLA
                if (number > 0) {
                    for (var i = 0; i <= number; i++) {
                        var w = input.value.indexOf("\n", position);
                        if (w != -1 && w < start) {
                            position = w + 1;
                            minus++;
                            
                        } else {
                            i = number;
                        }
                    }
                }
                s.text = inputStr;
                caretPositionAmp[pos] = rc.text.length + inputStr.length;
                re.move("character", caretPositionAmp[pos]);
                document.selection.empty();
                input.blur();
            }
            return this;
        } else if (typeof(input.selectionStart) == "number" && // MOZILLA support
                input.selectionStart != input.selectionEnd) {
            
            start = input.selectionStart;
            end = input.selectionEnd;
            input.value = input.value.substr(0, start) + inputStr + input.value.substr(end);
            position = start + inputStr.length;
            input.setSelectionRange(position, position); 
            input.scrollTop = mozScrollFix;
            return this;
        }
        return this;
    },

    //Set Selection in text
    setSelection: function(startPosition, endPosition) {
        startPosition = parseInt(startPosition);

        endPosition = parseInt(endPosition);
        
        var input = this.jquery ? this[0] : this; 
        input.focus ();
        if (typeof(input.selectionStart) != "number") {
            re = input.createTextRange();
            if (re.text.length < endPosition) {
                endPosition = re.text.length+1;
            }
        }
        if (endPosition < startPosition) {
            return this;
        }
        if (document.selection) { 
            var number = 0;
            var plus = 0;
            var position = 0;
            var plusEnd = 0;
            if (typeof(input.selectionStart) != "number") { // IE
                re.collapse(true); 
                re.moveEnd('character', endPosition); 
                re.moveStart('character', startPosition); 
                re.select(); 
                return this;
            } else if (typeof(input.selectionStart) == "number") {      // Opera
                if (input.value.match(/\n/g) != null) {
                    number = input.value.match(/\n/g).length;// number of EOL simbols
                }
                if (number > 0) {
                    for (var i = 0; i <= number; i++) {
                        var w = input.value.indexOf("\n", position);
                        if (w != -1 && w < startPosition) {
                            position = w + 1;
                            plus++;
                            plusEnd = plus;
                        } else if (w != -1 && w >= startPosition && w <= endPosition) {
                            if (w == startPosition + 1) {
                                plus--;
                                plusEnd--;
                                position = w + 1;
                                continue;
                            }
                            position = w + 1;
                            plusEnd++;
                        } else {
                            i = number;
                        }
                    }
                }
                startPosition = startPosition + plus;
                endPosition = endPosition + plusEnd;
                input.selectionStart = startPosition; 
                input.selectionEnd = endPosition;
                input.focus ();
                return this;
            } else {
                input.focus ();
                return this;
            }
        }
        else if (input.selectionStart || input.selectionStart == 0) {   // MOZILLA support
            input.focus ();
            window.getSelection().removeAllRanges();
            input.selectionStart = startPosition; 
            input.selectionEnd = endPosition; 
            input.focus ();
            return this;
        } 
    },

    // insert text at current caret position
    insertAtCaretPos: function(inputStr) {
        var input = this.jquery ? this[0] : this; 
        var start;
        var end;
        var position;
        var s;
        var re;
        var rc;
        var point;
        var minus = 0;
        var number = 0;
        var mozScrollFix = ( input.scrollTop == undefined ) ? 0 : input.scrollTop; 
        var obj = document.getElementsByTagName('TEXTAREA');
        var pos = 0;
        for (pos; pos < obj.length; pos++) {
            if (obj[pos] == input) {
                break;
            }
        }
        input.focus();
        if (document.selection && typeof(input.selectionStart) != "number") {
            if (input.value.match(/\n/g) != null) {
                number = input.value.match(/\n/g).length;// number of EOL simbols
            }
            point = parseInt(caretPositionAmp[pos]);
            if (number > 0) {
                for (var i = 0; i <= number; i++) {
                    var w = input.value.indexOf("\n", position);
                    if (w != -1 && w <= point) {
                        position = w + 1;
                        point = point - 1;
                        minus++;
                    } 
                }
            }
        }
        caretPositionAmp[pos] = parseInt(caretPositionAmp[pos]);

        // IE
        input.onkeyup = function() { // for IE because it loses caret position when focus changed
            if (document.selection && typeof(input.selectionStart) != "number") {
                input.focus();
                s = document.selection.createRange();
                re = input.createTextRange();
                rc = re.duplicate();
                re.moveToBookmark(s.getBookmark());
                rc.setEndPoint("EndToStart", re);
                caretPositionAmp[pos] = rc.text.length;
            }
            
        }

        input.onmouseup = function() { // for IE because it loses caret position when focus changed
            if (document.selection && typeof(input.selectionStart) != "number") {
                input.focus();
                s = document.selection.createRange();
                re = input.createTextRange();
                rc = re.duplicate();
                re.moveToBookmark(s.getBookmark());
                rc.setEndPoint("EndToStart", re);
                caretPositionAmp[pos] = rc.text.length;
            }
        }

        if (document.selection && typeof(input.selectionStart) != "number") {
            s = document.selection.createRange();
            if (s.text.length != 0) {
                return this;
            }
            re = input.createTextRange();
            textLength = re.text.length;
            rc = re.duplicate();
            re.moveToBookmark(s.getBookmark());
            rc.setEndPoint("EndToStart", re);
            start = rc.text.length; 
            if (caretPositionAmp[pos] > 0 && start ==0) {
                minus = caretPositionAmp[pos] - minus;
                re.move("character", minus);
                re.select();
                s = document.selection.createRange();
                caretPositionAmp[pos] += inputStr.length;
            } else if (!(caretPositionAmp[pos] >= 0) && textLength ==0) {
                s = document.selection.createRange();
                caretPositionAmp[pos] = inputStr.length + textLength;
            } else if (!(caretPositionAmp[pos] >= 0) && start ==0) {
                re.move("character", textLength);
                re.select();
                s = document.selection.createRange();
                caretPositionAmp[pos] = inputStr.length + textLength;
            } else if (!(caretPositionAmp[pos] >= 0) && start > 0) { 
                re.move("character", 0);
                document.selection.empty();
                re.select();
                s = document.selection.createRange();
                caretPositionAmp[pos] = start + inputStr.length;
            } else if (caretPositionAmp[pos] >= 0 && caretPositionAmp[pos] == textLength) { 
                if (textLength != 0) {
                    re.move("character", textLength);
                    re.select();
                } else {
                    re.move("character", 0);
                }
                s = document.selection.createRange();
                caretPositionAmp[pos] = inputStr.length + textLength;
            } else if (caretPositionAmp[pos] >= 0 && start != 0 && caretPositionAmp[pos] >= start) { 
                minus = caretPositionAmp[pos] - start;
                re.move("character", minus);
                document.selection.empty();
                re.select();
                s = document.selection.createRange();
                caretPositionAmp[pos] = caretPositionAmp[pos] + inputStr.length; 
            } else if (caretPositionAmp[pos] >= 0 && start != 0 && caretPositionAmp[pos] < start) { 
                re.move("character", 0);
                document.selection.empty();
                re.select();
                s = document.selection.createRange();
                caretPositionAmp[pos] = caretPositionAmp[pos] + inputStr.length; 
            } else { 
                document.selection.empty();
                re.select();
                s = document.selection.createRange();
                caretPositionAmp[pos] = caretPositionAmp[pos] + inputStr.length; 
            } 
            s.text = inputStr; 
            input.focus();

            return this;
        } else if (typeof(input.selectionStart) == "number" && // MOZILLA support
                input.selectionStart == input.selectionEnd) {
            position = input.selectionStart + inputStr.length;
            start = input.selectionStart;
            end = input.selectionEnd;
            input.value = input.value.substr(0, start) + inputStr + input.value.substr(end);
            input.setSelectionRange(position, position); 
            input.scrollTop = mozScrollFix; 
            return this;
        }
        return this;
    },

    // Set caret position
    setCaretPos: function(inputStr) {
        var input = this.jquery ? this[0] : this; 
        var s;
        var re;
        var position;
        var number = 0;
        var minus = 0;
        var w;
        var obj = document.getElementsByTagName('TEXTAREA');
        var pos = 0;
        for (pos; pos < obj.length; pos++) {
            if (obj[pos] == input) {
                break;
            }
        }
        input.focus();
        if (parseInt(inputStr) == 0) {
            return this;
        }
        //if (document.selection && typeof(input.selectionStart) == "number") {
        if (parseInt(inputStr) > 0) {
            inputStr = parseInt(inputStr) - 1;
            if (document.selection && typeof(input.selectionStart) == "number" && input.selectionStart == input.selectionEnd) {
                if (input.value.match(/\n/g) != null) {
                    number = input.value.match(/\n/g).length;// number of EOL simbols
                }
                if (number > 0) {
                    for (var i = 0; i <= number; i++) {
                        w = input.value.indexOf("\n", position);
                        if (w != -1 && w <= inputStr) {
                            position = w + 1;
                            inputStr = parseInt(inputStr) + 1;
                        } 
                    }
                }
            }
        } 
        else if (parseInt(inputStr) < 0) {
            inputStr = parseInt(inputStr) + 1;
            if (document.selection && typeof(input.selectionStart) != "number") {
                inputStr = input.value.length + parseInt(inputStr);
                if (input.value.match(/\n/g) != null) {
                    number = input.value.match(/\n/g).length;// number of EOL simbols
                }
                if (number > 0) {
                    for (var i = 0; i <= number; i++) {
                        w = input.value.indexOf("\n", position);
                        if (w != -1 && w <= inputStr) {
                            position = w + 1;
                            inputStr = parseInt(inputStr) - 1;
                            minus += 1;
                        } 
                    }
                    inputStr = inputStr + minus - number;
                }
            } else if (document.selection && typeof(input.selectionStart) == "number") {
                inputStr = input.value.length + parseInt(inputStr);
                if (input.value.match(/\n/g) != null) {
                    number = input.value.match(/\n/g).length;// number of EOL simbols
                }
                if (number > 0) {
                    inputStr = parseInt(inputStr) - number;
                    for (var i = 0; i <= number; i++) {
                        w = input.value.indexOf("\n", position);
                        if (w != -1 && w <= (inputStr)) {
                            position = w + 1;
                            inputStr = parseInt(inputStr) + 1;
                            minus += 1;
                        } 
                    }
                }
            } else { inputStr = input.value.length + parseInt(inputStr); }
        } else { return this; }
        // IE
        if (document.selection && typeof(input.selectionStart) != "number") {
            s = document.selection.createRange();
            if (s.text != 0) {
                return this;
            }
            re = input.createTextRange();
            re.collapse(true);
            re.moveEnd('character', inputStr);
            re.moveStart('character', inputStr);
            re.select();
            caretPositionAmp[pos] = inputStr;
            return this;
        } else if (typeof(input.selectionStart) == "number" && // MOZILLA support
                input.selectionStart == input.selectionEnd) {
            input.setSelectionRange(inputStr, inputStr); 
            return this;
        }
        return this;
    },

    countCharacters: function(str) {
        var input = this.jquery ? this[0] : this;
        if (input.value.match(/\r/g) != null) {
            return input.value.length - input.value.match(/\r/g).length;
        }
        return input.value.length;
    },

    setMaxLength: function(max, f) {
        this.each(function() {
            var input = this.jquery ? this[0] : this;
            var type = input.type;
            var isSelected;    
            var maxCharacters;
            // remove limit if input is a negative number
            if (parseInt(max) < 0) {
                max=100000000;
            }
            if (type == "text") {
                input.maxLength = max;
            }
            if (type == "textarea" || type == "text") {
                input.onkeypress = function(e) {
                    var spacesR = input.value.match(/\r/g);
                    maxCharacters = max;
                    if (spacesR != null) {
                        maxCharacters = parseInt(maxCharacters) + spacesR.length;
                    }
                    // get event
                    var key = e || event;
                    var keyCode = key.keyCode;
                    // check if any part of text is selected
                    if (document.selection) {
                        isSelected = document.selection.createRange().text.length > 0;
                    } else {
                        isSelected = input.selectionStart != input.selectionEnd;
                    }
                    if (input.value.length >= maxCharacters && (keyCode > 47 || keyCode == 32 ||
                            keyCode == 0 || keyCode == 13) && !key.ctrlKey && !key.altKey && !isSelected) {
                        input.value = input.value.substring(0,maxCharacters);
                        if (typeof(f) == "function") { f() } //callback function
                        return false;
                    }
                }
                input.onkeyup = function() { 
                    var spacesR = input.value.match(/\r/g);
                    var plus = 0;
                    var position = 0;
                    maxCharacters = max;
                    if (spacesR != null) {
                        for (var i = 0; i <= spacesR.length; i++) {
                            if (input.value.indexOf("\n", position) <= parseInt(max)) {
                                plus++;
                                position = input.value.indexOf("\n", position) + 1;
                            }
                        }
                        maxCharacters = parseInt(max) + plus;
                    } 
                    if (input.value.length > maxCharacters) {  
                        input.value = input.value.substring(0, maxCharacters); 
                        if (typeof(f) == "function") { f() }
                        return this;
                    }
                }
            } else { return this; }
        })
        return this;
    }
});

function goToPage(page, url, anchor, pageAsQuery)
{
	queryString = '';
	if (anchor && anchor.length) {
		anchor = '#' + anchor;
	}
	else {
		anchor = '';
	}
	
	if (page > 1) {
		if (pageAsQuery) { // stránkuji pomocí query stringu
			if (url.match('&page')) {
				url = url.split('&page');
				url = url[0];
			}			
			if (url.match('\\?')) { // pokračuji v query stringu
				var queryStringDelimiter = '&';
			}
			else { // zakládám nový query string
				var queryStringDelimiter = '?';
			}
			document.location = 'http://' + url + queryStringDelimiter + 'page=' + page + anchor;
		}
		else {
			if (url.match('\\?')) {
				url = url.split("?");
				queryString = '?' + url[1];
				url = url[0];
			}
			
			document.location = 'http://' + url + 'strankovani/' + page + '/' + queryString + anchor;
		}
	}
	else {
		if (pageAsQuery && url.match('&page')) {
			url = url.split('&page');
			url = url[0];
		}
		document.location = 'http://' + url + anchor;
	}
}

function buildSliderRange(name, from, to, fromValue, toValue)
{
	$("#slider-" + name).slider({
		range: true,
		min: from,
		max: to,
		values: [fromValue, toValue],
		slide: function(event, ui) {
			$("#slider-" + name + "-info").html(ui.values[0] + " - " + ui.values[1]);
			$("#" + name + "From").val(ui.values[0]);
			$("#" + name + "To").val(ui.values[1]);
		}
	});
	$("#slider-" + name + "-info").html($("#slider-" + name).slider("values", 0) + " - " + $("#slider-" + name).slider("values", 1));
}

/*!
 * jQuery Templates Plugin 1.0.0pre
 * http://github.com/jquery/jquery-tmpl
 * Requires jQuery 1.4.2
 *
 * Copyright Software Freedom Conservancy, Inc.
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 */
(function( jQuery, undefined ){
	var oldManip = jQuery.fn.domManip, tmplItmAtt = "_tmplitem", htmlExpr = /^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /,
		newTmplItems = {}, wrappedItems = {}, appendToTmplItems, topTmplItem = { key: 0, data: {} }, itemKey = 0, cloneIndex = 0, stack = [];

	function newTmplItem( options, parentItem, fn, data ) {
		// Returns a template item data structure for a new rendered instance of a template (a 'template item').
		// The content field is a hierarchical array of strings and nested items (to be
		// removed and replaced by nodes field of dom elements, once inserted in DOM).
		var newItem = {
			data: data || (data === 0 || data === false) ? data : (parentItem ? parentItem.data : {}),
			_wrap: parentItem ? parentItem._wrap : null,
			tmpl: null,
			parent: parentItem || null,
			nodes: [],
			calls: tiCalls,
			nest: tiNest,
			wrap: tiWrap,
			html: tiHtml,
			update: tiUpdate
		};
		if ( options ) {
			jQuery.extend( newItem, options, { nodes: [], parent: parentItem });
		}
		if ( fn ) {
			// Build the hierarchical content to be used during insertion into DOM
			newItem.tmpl = fn;
			newItem._ctnt = newItem._ctnt || newItem.tmpl( jQuery, newItem );
			newItem.key = ++itemKey;
			// Keep track of new template item, until it is stored as jQuery Data on DOM element
			(stack.length ? wrappedItems : newTmplItems)[itemKey] = newItem;
		}
		return newItem;
	}

	// Override appendTo etc., in order to provide support for targeting multiple elements. (This code would disappear if integrated in jquery core).
	jQuery.each({
		appendTo: "append",
		prependTo: "prepend",
		insertBefore: "before",
		insertAfter: "after",
		replaceAll: "replaceWith"
	}, function( name, original ) {
		jQuery.fn[ name ] = function( selector ) {
			var ret = [], insert = jQuery( selector ), elems, i, l, tmplItems,
				parent = this.length === 1 && this[0].parentNode;

			appendToTmplItems = newTmplItems || {};
			if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
				insert[ original ]( this[0] );
				ret = this;
			} else {
				for ( i = 0, l = insert.length; i < l; i++ ) {
					cloneIndex = i;
					elems = (i > 0 ? this.clone(true) : this).get();
					jQuery( insert[i] )[ original ]( elems );
					ret = ret.concat( elems );
				}
				cloneIndex = 0;
				ret = this.pushStack( ret, name, insert.selector );
			}
			tmplItems = appendToTmplItems;
			appendToTmplItems = null;
			jQuery.tmpl.complete( tmplItems );
			return ret;
		};
	});

	jQuery.fn.extend({
		// Use first wrapped element as template markup.
		// Return wrapped set of template items, obtained by rendering template against data.
		tmpl: function( data, options, parentItem ) {
			return jQuery.tmpl( this[0], data, options, parentItem );
		},

		// Find which rendered template item the first wrapped DOM element belongs to
		tmplItem: function() {
			return jQuery.tmplItem( this[0] );
		},

		// Consider the first wrapped element as a template declaration, and get the compiled template or store it as a named template.
		template: function( name ) {
			return jQuery.template( name, this[0] );
		},

		domManip: function( args, table, callback, options ) {
			if ( args[0] && jQuery.isArray( args[0] )) {
				var dmArgs = jQuery.makeArray( arguments ), elems = args[0], elemsLength = elems.length, i = 0, tmplItem;
				while ( i < elemsLength && !(tmplItem = jQuery.data( elems[i++], "tmplItem" ))) {}
				if ( tmplItem && cloneIndex ) {
					dmArgs[2] = function( fragClone ) {
						// Handler called by oldManip when rendered template has been inserted into DOM.
						jQuery.tmpl.afterManip( this, fragClone, callback );
					};
				}
				oldManip.apply( this, dmArgs );
			} else {
				oldManip.apply( this, arguments );
			}
			cloneIndex = 0;
			if ( !appendToTmplItems ) {
				jQuery.tmpl.complete( newTmplItems );
			}
			return this;
		}
	});

	jQuery.extend({
		// Return wrapped set of template items, obtained by rendering template against data.
		tmpl: function( tmpl, data, options, parentItem ) {
			var ret, topLevel = !parentItem;
			if ( topLevel ) {
				// This is a top-level tmpl call (not from a nested template using {{tmpl}})
				parentItem = topTmplItem;
				tmpl = jQuery.template[tmpl] || jQuery.template( null, tmpl );
				wrappedItems = {}; // Any wrapped items will be rebuilt, since this is top level
			} else if ( !tmpl ) {
				// The template item is already associated with DOM - this is a refresh.
				// Re-evaluate rendered template for the parentItem
				tmpl = parentItem.tmpl;
				newTmplItems[parentItem.key] = parentItem;
				parentItem.nodes = [];
				if ( parentItem.wrapped ) {
					updateWrapped( parentItem, parentItem.wrapped );
				}
				// Rebuild, without creating a new template item
				return jQuery( build( parentItem, null, parentItem.tmpl( jQuery, parentItem ) ));
			}
			if ( !tmpl ) {
				return []; // Could throw...
			}
			if ( typeof data === "function" ) {
				data = data.call( parentItem || {} );
			}
			if ( options && options.wrapped ) {
				updateWrapped( options, options.wrapped );
			}
			ret = jQuery.isArray( data ) ?
				jQuery.map( data, function( dataItem ) {
					return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem ) : null;
				}) :
				[ newTmplItem( options, parentItem, tmpl, data ) ];
			return topLevel ? jQuery( build( parentItem, null, ret ) ) : ret;
		},

		// Return rendered template item for an element.
		tmplItem: function( elem ) {
			var tmplItem;
			if ( elem instanceof jQuery ) {
				elem = elem[0];
			}
			while ( elem && elem.nodeType === 1 && !(tmplItem = jQuery.data( elem, "tmplItem" )) && (elem = elem.parentNode) ) {}
			return tmplItem || topTmplItem;
		},

		// Set:
		// Use $.template( name, tmpl ) to cache a named template,
		// where tmpl is a template string, a script element or a jQuery instance wrapping a script element, etc.
		// Use $( "selector" ).template( name ) to provide access by name to a script block template declaration.

		// Get:
		// Use $.template( name ) to access a cached template.
		// Also $( selectorToScriptBlock ).template(), or $.template( null, templateString )
		// will return the compiled template, without adding a name reference.
		// If templateString includes at least one HTML tag, $.template( templateString ) is equivalent
		// to $.template( null, templateString )
		template: function( name, tmpl ) {
			if (tmpl) {
				// Compile template and associate with name
				if ( typeof tmpl === "string" ) {
					// This is an HTML string being passed directly in.
					tmpl = buildTmplFn( tmpl );
				} else if ( tmpl instanceof jQuery ) {
					tmpl = tmpl[0] || {};
				}
				if ( tmpl.nodeType ) {
					// If this is a template block, use cached copy, or generate tmpl function and cache.
					tmpl = jQuery.data( tmpl, "tmpl" ) || jQuery.data( tmpl, "tmpl", buildTmplFn( tmpl.innerHTML ));
					// Issue: In IE, if the container element is not a script block, the innerHTML will remove quotes from attribute values whenever the value does not include white space.
					// This means that foo="${x}" will not work if the value of x includes white space: foo="${x}" -> foo=value of x.
					// To correct this, include space in tag: foo="${ x }" -> foo="value of x"
				}
				return typeof name === "string" ? (jQuery.template[name] = tmpl) : tmpl;
			}
			// Return named compiled template
			return name ? (typeof name !== "string" ? jQuery.template( null, name ):
				(jQuery.template[name] ||
					// If not in map, and not containing at least on HTML tag, treat as a selector.
					// (If integrated with core, use quickExpr.exec)
					jQuery.template( null, htmlExpr.test( name ) ? name : jQuery( name )))) : null;
		},

		encode: function( text ) {
			// Do HTML encoding replacing < > & and ' and " by corresponding entities.
			return ("" + text).split("<").join("&lt;").split(">").join("&gt;").split('"').join("&#34;").split("'").join("&#39;");
		}
	});

	jQuery.extend( jQuery.tmpl, {
		tag: {
			"tmpl": {
				_default: { $2: "null" },
				open: "if($notnull_1){__=__.concat($item.nest($1,$2));}"
				// tmpl target parameter can be of type function, so use $1, not $1a (so not auto detection of functions)
				// This means that {{tmpl foo}} treats foo as a template (which IS a function).
				// Explicit parens can be used if foo is a function that returns a template: {{tmpl foo()}}.
			},
			"wrap": {
				_default: { $2: "null" },
				open: "$item.calls(__,$1,$2);__=[];",
				close: "call=$item.calls();__=call._.concat($item.wrap(call,__));"
			},
			"each": {
				_default: { $2: "$index, $value" },
				open: "if($notnull_1){$.each($1a,function($2){with(this){",
				close: "}});}"
			},
			"if": {
				open: "if(($notnull_1) && $1a){",
				close: "}"
			},
			"else": {
				_default: { $1: "true" },
				open: "}else if(($notnull_1) && $1a){"
			},
			"html": {
				// Unecoded expression evaluation.
				open: "if($notnull_1){__.push($1a);}"
			},
			"=": {
				// Encoded expression evaluation. Abbreviated form is ${}.
				_default: { $1: "$data" },
				open: "if($notnull_1){__.push($.encode($1a));}"
			},
			"!": {
				// Comment tag. Skipped by parser
				open: ""
			}
		},

		// This stub can be overridden, e.g. in jquery.tmplPlus for providing rendered events
		complete: function( items ) {
			newTmplItems = {};
		},

		// Call this from code which overrides domManip, or equivalent
		// Manage cloning/storing template items etc.
		afterManip: function afterManip( elem, fragClone, callback ) {
			// Provides cloned fragment ready for fixup prior to and after insertion into DOM
			var content = fragClone.nodeType === 11 ?
				jQuery.makeArray(fragClone.childNodes) :
				fragClone.nodeType === 1 ? [fragClone] : [];

			// Return fragment to original caller (e.g. append) for DOM insertion
			callback.call( elem, fragClone );

			// Fragment has been inserted:- Add inserted nodes to tmplItem data structure. Replace inserted element annotations by jQuery.data.
			storeTmplItems( content );
			cloneIndex++;
		}
	});

	//========================== Private helper functions, used by code above ==========================

	function build( tmplItem, nested, content ) {
		// Convert hierarchical content into flat string array
		// and finally return array of fragments ready for DOM insertion
		var frag, ret = content ? jQuery.map( content, function( item ) {
			return (typeof item === "string") ?
				// Insert template item annotations, to be converted to jQuery.data( "tmplItem" ) when elems are inserted into DOM.
				(tmplItem.key ? item.replace( /(<\w+)(?=[\s>])(?![^>]*_tmplitem)([^>]*)/g, "$1 " + tmplItmAtt + "=\"" + tmplItem.key + "\" $2" ) : item) :
				// This is a child template item. Build nested template.
				build( item, tmplItem, item._ctnt );
		}) :
		// If content is not defined, insert tmplItem directly. Not a template item. May be a string, or a string array, e.g. from {{html $item.html()}}.
		tmplItem;
		if ( nested ) {
			return ret;
		}

		// top-level template
		ret = ret.join("");

		// Support templates which have initial or final text nodes, or consist only of text
		// Also support HTML entities within the HTML markup.
		ret.replace( /^\s*([^<\s][^<]*)?(<[\w\W]+>)([^>]*[^>\s])?\s*$/, function( all, before, middle, after) {
			frag = jQuery( middle ).get();

			storeTmplItems( frag );
			if ( before ) {
				frag = unencode( before ).concat(frag);
			}
			if ( after ) {
				frag = frag.concat(unencode( after ));
			}
		});
		return frag ? frag : unencode( ret );
	}

	function unencode( text ) {
		// Use createElement, since createTextNode will not render HTML entities correctly
		var el = document.createElement( "div" );
		el.innerHTML = text;
		return jQuery.makeArray(el.childNodes);
	}

	// Generate a reusable function that will serve to render a template against data
	function buildTmplFn( markup ) {
		return new Function("jQuery","$item",
			// Use the variable __ to hold a string array while building the compiled template. (See https://github.com/jquery/jquery-tmpl/issues#issue/10).
			"var $=jQuery,call,__=[],$data=$item.data;" +

			// Introduce the data as local variables using with(){}
			"with($data){__.push('" +

			// Convert the template into pure JavaScript
			jQuery.trim(markup)
				.replace( /([\\'])/g, "\\$1" )
				.replace( /[\r\t\n]/g, " " )
				.replace( /\$\{([^\}]*)\}/g, "{{= $1}}" )
				.replace( /\{\{(\/?)(\w+|.)(?:\(((?:[^\}]|\}(?!\}))*?)?\))?(?:\s+(.*?)?)?(\(((?:[^\}]|\}(?!\}))*?)\))?\s*\}\}/g,
				function( all, slash, type, fnargs, target, parens, args ) {
					var tag = jQuery.tmpl.tag[ type ], def, expr, exprAutoFnDetect;
					if ( !tag ) {
						throw "Unknown template tag: " + type;
					}
					def = tag._default || [];
					if ( parens && !/\w$/.test(target)) {
						target += parens;
						parens = "";
					}
					if ( target ) {
						target = unescape( target );
						args = args ? ("," + unescape( args ) + ")") : (parens ? ")" : "");
						// Support for target being things like a.toLowerCase();
						// In that case don't call with template item as 'this' pointer. Just evaluate...
						expr = parens ? (target.indexOf(".") > -1 ? target + unescape( parens ) : ("(" + target + ").call($item" + args)) : target;
						exprAutoFnDetect = parens ? expr : "(typeof(" + target + ")==='function'?(" + target + ").call($item):(" + target + "))";
					} else {
						exprAutoFnDetect = expr = def.$1 || "null";
					}
					fnargs = unescape( fnargs );
					return "');" +
						tag[ slash ? "close" : "open" ]
							.split( "$notnull_1" ).join( target ? "typeof(" + target + ")!=='undefined' && (" + target + ")!=null" : "true" )
							.split( "$1a" ).join( exprAutoFnDetect )
							.split( "$1" ).join( expr )
							.split( "$2" ).join( fnargs || def.$2 || "" ) +
						"__.push('";
				}) +
			"');}return __;"
		);
	}
	function updateWrapped( options, wrapped ) {
		// Build the wrapped content.
		options._wrap = build( options, true,
			// Suport imperative scenario in which options.wrapped can be set to a selector or an HTML string.
			jQuery.isArray( wrapped ) ? wrapped : [htmlExpr.test( wrapped ) ? wrapped : jQuery( wrapped ).html()]
		).join("");
	}

	function unescape( args ) {
		return args ? args.replace( /\\'/g, "'").replace(/\\\\/g, "\\" ) : null;
	}
	function outerHtml( elem ) {
		var div = document.createElement("div");
		div.appendChild( elem.cloneNode(true) );
		return div.innerHTML;
	}

	// Store template items in jQuery.data(), ensuring a unique tmplItem data data structure for each rendered template instance.
	function storeTmplItems( content ) {
		var keySuffix = "_" + cloneIndex, elem, elems, newClonedItems = {}, i, l, m;
		for ( i = 0, l = content.length; i < l; i++ ) {
			if ( (elem = content[i]).nodeType !== 1 ) {
				continue;
			}
			elems = elem.getElementsByTagName("*");
			for ( m = elems.length - 1; m >= 0; m-- ) {
				processItemKey( elems[m] );
			}
			processItemKey( elem );
		}
		function processItemKey( el ) {
			var pntKey, pntNode = el, pntItem, tmplItem, key;
			// Ensure that each rendered template inserted into the DOM has its own template item,
			if ( (key = el.getAttribute( tmplItmAtt ))) {
				while ( pntNode.parentNode && (pntNode = pntNode.parentNode).nodeType === 1 && !(pntKey = pntNode.getAttribute( tmplItmAtt ))) { }
				if ( pntKey !== key ) {
					// The next ancestor with a _tmplitem expando is on a different key than this one.
					// So this is a top-level element within this template item
					// Set pntNode to the key of the parentNode, or to 0 if pntNode.parentNode is null, or pntNode is a fragment.
					pntNode = pntNode.parentNode ? (pntNode.nodeType === 11 ? 0 : (pntNode.getAttribute( tmplItmAtt ) || 0)) : 0;
					if ( !(tmplItem = newTmplItems[key]) ) {
						// The item is for wrapped content, and was copied from the temporary parent wrappedItem.
						tmplItem = wrappedItems[key];
						tmplItem = newTmplItem( tmplItem, newTmplItems[pntNode]||wrappedItems[pntNode] );
						tmplItem.key = ++itemKey;
						newTmplItems[itemKey] = tmplItem;
					}
					if ( cloneIndex ) {
						cloneTmplItem( key );
					}
				}
				el.removeAttribute( tmplItmAtt );
			} else if ( cloneIndex && (tmplItem = jQuery.data( el, "tmplItem" )) ) {
				// This was a rendered element, cloned during append or appendTo etc.
				// TmplItem stored in jQuery data has already been cloned in cloneCopyEvent. We must replace it with a fresh cloned tmplItem.
				cloneTmplItem( tmplItem.key );
				newTmplItems[tmplItem.key] = tmplItem;
				pntNode = jQuery.data( el.parentNode, "tmplItem" );
				pntNode = pntNode ? pntNode.key : 0;
			}
			if ( tmplItem ) {
				pntItem = tmplItem;
				// Find the template item of the parent element.
				// (Using !=, not !==, since pntItem.key is number, and pntNode may be a string)
				while ( pntItem && pntItem.key != pntNode ) {
					// Add this element as a top-level node for this rendered template item, as well as for any
					// ancestor items between this item and the item of its parent element
					pntItem.nodes.push( el );
					pntItem = pntItem.parent;
				}
				// Delete content built during rendering - reduce API surface area and memory use, and avoid exposing of stale data after rendering...
				delete tmplItem._ctnt;
				delete tmplItem._wrap;
				// Store template item as jQuery data on the element
				jQuery.data( el, "tmplItem", tmplItem );
			}
			function cloneTmplItem( key ) {
				key = key + keySuffix;
				tmplItem = newClonedItems[key] =
					(newClonedItems[key] || newTmplItem( tmplItem, newTmplItems[tmplItem.parent.key + keySuffix] || tmplItem.parent ));
			}
		}
	}

	//---- Helper functions for template item ----

	function tiCalls( content, tmpl, data, options ) {
		if ( !content ) {
			return stack.pop();
		}
		stack.push({ _: content, tmpl: tmpl, item:this, data: data, options: options });
	}

	function tiNest( tmpl, data, options ) {
		// nested template, using {{tmpl}} tag
		return jQuery.tmpl( jQuery.template( tmpl ), data, options, this );
	}

	function tiWrap( call, wrapped ) {
		// nested template, using {{wrap}} tag
		var options = call.options || {};
		options.wrapped = wrapped;
		// Apply the template, which may incorporate wrapped content,
		return jQuery.tmpl( jQuery.template( call.tmpl ), call.data, options, call.item );
	}

	function tiHtml( filter, textOnly ) {
		var wrapped = this._wrap;
		return jQuery.map(
			jQuery( jQuery.isArray( wrapped ) ? wrapped.join("") : wrapped ).filter( filter || "*" ),
			function(e) {
				return textOnly ?
					e.innerText || e.textContent :
					e.outerHTML || outerHtml(e);
			});
	}

	function tiUpdate() {
		var coll = this.nodes;
		jQuery.tmpl( null, null, null, this).insertBefore( coll[0] );
		jQuery( coll ).remove();
	}
})( jQuery );

/*!
 * jQuery Expander Plugin v1.3
 *
 * Date: Sat Sep 17 00:37:34 2011 EDT
 * Requires: jQuery v1.3+
 *
 * Copyright 2011, Karl Swedberg
 * Dual licensed under the MIT and GPL licenses (just like jQuery):
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 *
 *
 *
*/
(function($) {
  $.expander = {
    version: '1.3',
    defaults: {
      // the number of characters at which the contents will be sliced into two parts.
      slicePoint: 100,

      // whether to keep the last word of the summary whole (true) or let it slice in the middle of a word (false)
      preserveWords: true,

      // widow: a threshold of sorts for whether to initially hide/collapse part of the element's contents.
      // If after slicing the contents in two there are fewer words in the second part than
      // the value set by widow, we won't bother hiding/collapsing anything.
      widow: 4,

      // text displayed in a link instead of the hidden part of the element.
      // clicking this will expand/show the hidden/collapsed text
      expandText: 'read more',
      expandPrefix: '&hellip; ',

      // class names for summary element and detail element
      summaryClass: 'summary',
      detailClass: 'details',

      // class names for <span> around "read-more" link and "read-less" link
      moreClass: 'read-more',
      lessClass: 'read-less',

      // number of milliseconds after text has been expanded at which to collapse the text again.
      // when 0, no auto-collapsing
      collapseTimer: 0,

      // effects for expanding and collapsing
      expandEffect: 'fadeIn',
      expandSpeed: 250,
      collapseEffect: 'fadeOut',
      collapseSpeed: 200,

      // allow the user to re-collapse the expanded text.
      userCollapse: true,

      // text to use for the link to re-collapse the text
      userCollapseText: 'read less',
      userCollapsePrefix: ' ',


      // all callback functions have the this keyword mapped to the element in the jQuery set when .expander() is called

      onSlice: null, // function() {}
      beforeExpand: null, // function() {},
      afterExpand: null, // function() {},
      onCollapse: null // function(byUser) {}
    }
  };

  $.fn.expander = function(options) {

    var opts = $.extend({}, $.expander.defaults, options),
        rSelfClose = /^<(?:area|br|col|embed|hr|img|input|link|meta|param).*>$/i,
        rAmpWordEnd = /(&(?:[^;]+;)?|\w+)$/,
        rOpenCloseTag = /<\/?(\w+)[^>]*>/g,
        rOpenTag = /<(\w+)[^>]*>/g,
        rCloseTag = /<\/(\w+)>/g,
        rTagPlus = /^<[^>]+>.?/,
        delayedCollapse;

    this.each(function() {
      var i, l, tmp, summTagLess, summOpens, summCloses, lastCloseTag, detailText,
          $thisDetails, $readMore,
          openTagsForDetails = [],
          closeTagsForsummaryText = [],
          defined = {},
          thisEl = this,
          $this = $(this),
          $summEl = $([]),
          o = $.meta ? $.extend({}, opts, $this.data()) : opts,
          hasDetails = !!$this.find('.' + o.detailClass).length,
          hasBlocks = !!$this.find('*').filter(function() {
            var display = $(this).css('display');
            return (/^block|table|list/).test(display);
          }).length,
          el = hasBlocks ? 'div' : 'span',
          detailSelector = el + '.' + o.detailClass,
          moreSelector = 'span.' + o.moreClass,
          expandSpeed = o.expandSpeed || 0,
          allHtml = $.trim( $this.html() ),
          allText = $.trim( $this.text() ),
          summaryText = allHtml.slice(0, o.slicePoint);

      // bail out if we've already set up the expander on this element
      if ( $.data(this, 'expander') ) {
        return;
      }
      $.data(this, 'expander', true);

      // determine which callback functions are defined
      $.each(['onSlice','beforeExpand', 'afterExpand', 'onCollapse'], function(index, val) {
        defined[val] = $.isFunction(o[val]);
      });

      // back up if we're in the middle of a tag or word
      summaryText = backup(summaryText);

      // summary text sans tags length
      summTagless = summaryText.replace(rOpenCloseTag,'').length;

      // add more characters to the summary, one for each character in the tags
      while (summTagless < o.slicePoint) {
        newChar = allHtml.charAt(summaryText.length);
        if (newChar == '<') {
          newChar = allHtml.slice(summaryText.length).match(rTagPlus)[0];
        }
        summaryText += newChar;
        summTagless++;
      }

      summaryText = backup(summaryText, o.preserveWords);

      // separate open tags from close tags and clean up the lists
      summOpens = summaryText.match(rOpenTag) || [];
      summCloses = summaryText.match(rCloseTag) || [];

      // filter out self-closing tags
      tmp = [];
      $.each(summOpens, function(index, val) {
        if ( !rSelfClose.test(val) ) {
          tmp.push(val);
        }
      });
      summOpens = tmp;

      // strip close tags to just the tag name
      l = summCloses.length;
      for (i = 0; i < l; i++) {
        summCloses[i] = summCloses[i].replace(rCloseTag, '$1');
      }

      // tags that start in summary and end in detail need:
      // a). close tag at end of summary
      // b). open tag at beginning of detail
      $.each(summOpens, function(index, val) {
        var thisTagName = val.replace(rOpenTag, '$1');
        var closePosition = $.inArray(thisTagName, summCloses);
        if (closePosition === -1) {
          openTagsForDetails.push(val);
          closeTagsForsummaryText.push('</' + thisTagName + '>');

        } else {
          summCloses.splice(closePosition, 1);
        }
      });

      // reverse the order of the close tags for the summary so they line up right
      closeTagsForsummaryText.reverse();

      // create necessary summary and detail elements if they don't already exist
      if ( !hasDetails ) {

        // end script if detail has fewer words than widow option
        detailText = allHtml.slice(summaryText.length);
        if ( detailText.split(/\s+/).length < o.widow && !hasDetails ) {
          return;
        }

        // otherwise, continue...
        lastCloseTag = closeTagsForsummaryText.pop() || '';
        summaryText += closeTagsForsummaryText.join('');
        detailText = openTagsForDetails.join('') + detailText;

      } else {
        // assume that even if there are details, we still need readMore/readLess/summary elements
        // (we already bailed out earlier when readMore el was found)
        // but we need to create els differently

        // remove the detail from the rest of the content
        detailText = $this.find(detailSelector).remove().html();

        // The summary is what's left
        summaryText = $this.html();

        // allHtml is the summary and detail combined (this is needed when content has block-level elements)
        allHtml = summaryText + detailText;

        lastCloseTag = '';
      }
      o.moreLabel = $this.find(moreSelector).length ? '' : buildMoreLabel(o);

      if (hasBlocks) {
        detailText = allHtml;
      }
      summaryText += lastCloseTag;

      // onSlice callback
      o.summary = summaryText;
      o.details = detailText;
      o.lastCloseTag = lastCloseTag;

      if (defined.onSlice) {
        // user can choose to return a modified options object
        // one last chance for user to change the options. sneaky, huh?
        // but could be tricky so use at your own risk.
        tmp = o.onSlice.call(thisEl, o);

      // so, if the returned value from the onSlice function is an object with a details property, we'll use that!
        o = tmp && tmp.details ? tmp : o;
      }

      // build the html with summary and detail and use it to replace old contents
      var html = buildHTML(o, hasBlocks);
      $this.html( html );

      // set up details and summary for expanding/collapsing
      $thisDetails = $this.find(detailSelector);
      $readMore = $this.find(moreSelector);
      $thisDetails.hide();
      $readMore.find('a').unbind('click.expander').bind('click.expander', expand);

      $summEl = $this.find('div.' + o.summaryClass);

      if ( o.userCollapse && !$this.find('span.' + o.lessClass).length ) {
        $this
        .find(detailSelector)
        .append('<span class="' + o.lessClass + '">' + o.userCollapsePrefix + '<a href="#">' + o.userCollapseText + '</a></span>');
      }

      $this
      .find('span.' + o.lessClass + ' a')
      .unbind('click.expander')
      .bind('click.expander', function(event) {
        event.preventDefault();
        clearTimeout(delayedCollapse);
        var $detailsCollapsed = $(this).closest(detailSelector);
        reCollapse(o, $detailsCollapsed);
        if (defined.onCollapse) {
          o.onCollapse.call(thisEl, true);
        }
      });

      function expand(event) {
        event.preventDefault();
        $readMore.hide();
        $summEl.hide();
        if (defined.beforeExpand) {
          o.beforeExpand.call(thisEl);
        }

        $thisDetails.stop(false, true)[o.expandEffect](expandSpeed, function() {
          $thisDetails.css({zoom: ''});
          if (defined.afterExpand) {o.afterExpand.call(thisEl);}
          delayCollapse(o, $thisDetails, thisEl);
        });
      }

    }); // this.each

    function buildHTML(o, blocks) {
      var el = 'span',
          summary = o.summary;
      if ( blocks ) {
        el = 'div';
        // tuck the moreLabel inside the last close tag
        summary = summary.replace(/(<\/[^>]+>)\s*$/, o.moreLabel + '$1');

        // and wrap it in a div
        summary = '<div class="' + o.summaryClass + '">' + summary + '</div>';
      } else {
        summary += o.moreLabel;
      }

      return [
        summary,
        '<',
          el + ' class="' + o.detailClass + '"',
        '>',
          o.details,
        '</' + el + '>'
        ].join('');
    }

    function buildMoreLabel(o) {
      var ret = '<span class="' + o.moreClass + '">' + o.expandPrefix;
      ret += '<a href="#">' + o.expandText + '</a></span>';
      return ret;
    }

    function backup(txt, preserveWords) {
      if ( txt.lastIndexOf('<') > txt.lastIndexOf('>') ) {
        txt = txt.slice( 0, txt.lastIndexOf('<') );
      }
      if (preserveWords) {
        txt = txt.replace(rAmpWordEnd,'');
      }
      return txt;
    }

    function reCollapse(o, el) {
      el.stop(true, true)[o.collapseEffect](o.collapseSpeed, function() {
        var prevMore = el.prev('span.' + o.moreClass).show();
        if (!prevMore.length) {
          el.parent().children('div.' + o.summaryClass).show()
            .find('span.' + o.moreClass).show();
        }
      });
    }

    function delayCollapse(option, $collapseEl, thisEl) {
      if (option.collapseTimer) {
        delayedCollapse = setTimeout(function() {
          reCollapse(option, $collapseEl);
          if ( $.isFunction(option.onCollapse) ) {
            option.onCollapse.call(thisEl, false);
          }
        }, option.collapseTimer);
      }
    }

    return this;
  };

  // plugin defaults
  $.fn.expander.defaults = $.expander.defaults;
})(jQuery);

/**
 * Editace textových polí - upravená Textyla
 */
var Text = function (text, prefix, imageUploader) {
	// textové pole, které se bude upravovat v tomto textu
	this.text = text;
	
	// odkaz na uploader obrázků
	this.imageUploader = imageUploader;
	
	// prefix pro standardní názvy tříd
	this.prefix = prefix;
}

Text.prototype.lineDelimiter = null; // oddělovač nových řádků
Text.prototype = {
	init: function () {
		var Text = this;
				
		// zaregistruji základní klávesové zkratky pro textarea
		this.text.keydown(function(e){ // stisknutí klávesy
		     if(e.keyCode == 66 && e.ctrlKey) { // CTRL + B
		    	 Text.replaceWithPrePost('**', '**');
		    	 e.preventDefault();
		     }
		     else if (e.keyCode == 73 && e.ctrlKey) { // CTRL + I
		    	 Text.replaceWithPrePost('*', '*');
		    	 e.preventDefault();
		     }
		});
		
		// kliknutí na zobrazení náhledu
		$('#' + this.prefix + 'ShowPreview').click(function (event) {
			event.preventDefault();
			Text.preview($('#' + Text.prefix + 'Form'), $('#' + Text.prefix + 'PreviewLoading'), $('#' + Text.prefix + 'Preview'), $('#' + Text.prefix + 'PreviewIn'));
		});

		// kliknutí na zavření náhledu
		$('#' + this.prefix + 'PreviewClose').click(function (event) {
			event.preventDefault();
			$('#' + Text.prefix + 'Preview').hide();
			$('#' + Text.prefix + 'Form').show();
		});

		// kliknutí na přidání fotek
		$('#' + this.prefix + 'ImagesAdd').click(function (event) {
			event.preventDefault();
			$('#' + Text.prefix + 'Images').show();
			// Text.imageUploader.refresh();
			$(this).hide();
		});

		// kliknutí na storno v jakémkoliv dialogu
		$('input[action="dialogStorno"]').click(function (event) {
			event.preventDefault();
			$(this).parent().dialog('close');
		});
		
		// kliknutí na toolbar - přidání textu před a za
		$('a[action="replaceWith"]').click(function (event) {
			event.preventDefault();
			Text.replaceWithPrePost($(this).attr('pre'), $(this).attr('post'));
		});

		// kliknutí na toolbar - přidání textu před a za a zavření dialogu
		$('a[action="replaceWithAndClose"]').click(function (event) {
			event.preventDefault();
			Text.replaceWithPrePost($(this).attr('pre'), $(this).attr('post'));
			$('#' + $(this).attr('close')).dialog('close');
		});

		// kliknutí na toolbar - přidání textu na pozici kurzoru
		$('a[action="insertAt"]').click(function (event) {
			event.preventDefault();
			Text.insertAt($(this).attr('value'));
		});

		// klikání na toolbar - přidání seznamu
		$('a[action="replaceWithList"]').click(function (event) {
			event.preventDefault();
			Text.replaceWithList($(this).attr('type'));
		});

		/*var dialogSetting = {
			modal: false,
            autoOpen: false
		};
		
		// vytvořím si jednotlivé dialogy
		$('#' + Text.prefix + 'DialogColor').dialog(dialogSetting);
		$('#' + Text.prefix + 'DialogImage').dialog(dialogSetting);
		$('#' + Text.prefix + 'DialogTable').dialog(dialogSetting);
		$('#' + Text.prefix + 'DialogLink').dialog(dialogSetting);*/
		
		// kliknutí na toolbar - dialog s barvami
		$('#' + this.prefix + 'DialogColorLink').click(function (event) {
			event.preventDefault();
			$('#' + Text.prefix + 'DialogColor').dialog('open');
		});

		// kliknutí na toolbar - dialog s externím obrázkem
		$('#' + this.prefix + 'DialogImageLink').click(function (event) {
			event.preventDefault();
			$('#' + Text.prefix + 'DialogImage').dialog('open');
			$('#' + Text.prefix + 'DialogImageUrl').val('');
		});
		
		// kliknutí na toolbar - dialog s tabulkou
		$('#' + this.prefix + 'DialogTableLink').click(function (event) {
			event.preventDefault();
			$('#' + Text.prefix + 'DialogTableCols').val(2);
			$('#' + Text.prefix + 'DialogTableRows').val(2);
			$('#' + Text.prefix + 'DialogTable').dialog('open');
		});

		// kliknutí na toolbar - dialog s odkazem
		$('#' + this.prefix + 'DialogLinkLink').click(function (event) {
			event.preventDefault();
			var selection = Text.text.getSelection();
			$('#' + Text.prefix + 'DialogLinkUrl').val('');
			
			if (selection.length > 0) {
				$('#' + Text.prefix + 'DialogLinkAnchor').val(selection.text);
			}
			else {
				$('#' + Text.prefix + 'DialogLinkAnchor').val('');
			}
			
			$('#' + Text.prefix + 'DialogLink').dialog('open');

		});
		
		// kliknutí na přidání obrázku v dialogu
		$('#' + this.prefix + 'DialogImageOk').click(function (event) {
			event.preventDefault();
			var url = jQuery.trim($('#' + Text.prefix + 'DialogImageUrl').val());
			if (!url) {
				alert('Nezadali jste URL adresu obrázku');
			}
			Text.imageExternal(url);
			$('#' + Text.prefix + 'DialogImage').dialog('close');
		});

		// kliknutí na přidání odkazu
		$('#' + this.prefix + 'DialogLinkOk').click(function (event) {
			event.preventDefault();
			if (!Text.link($('#' + Text.prefix + 'DialogLinkUrl').val(), $('#' + Text.prefix + 'DialogLinkAnchor').val())) {
				alert('Nezadali jste cílovou adresu odkazu');
				return false;
			}
			
			$('#' + Text.prefix + 'DialogLink').dialog('close');
		});

		// kliknutí na přidání tabulky
		$('#' + Text.prefix + 'DialogTableOk').click(function (event) {
			event.preventDefault();
			if (Text.table($('#' + Text.prefix + 'DialogTableCols').val(), $('#' + Text.prefix + 'DialogTableRows').val(), $('#' + Text.prefix + 'DialogTableHeader').val())) {
				$('#' + Text.prefix + 'DialogTable').dialog('close');
			}
		});
	},

	// zobrazení náhledu textu
	preview: function (form, loading, preview, previewIn) {
		var textValue = jQuery.trim(this.text.val());
		
		if (!textValue) {
			alert('Nezadali jste žádný text, není co zobrazit');
			return false;
		}
		
		form.hide(); // schovám celý formulář
		preview.hide(); // schovám celý náhled
		loading.show(); // zobrazím informaci informace o načítání náhledu
		previewIn.load('http://' + document.domain + '/ajax/?controller=Ajax&action=texytohtml', {'texy' : textValue}, function () {
			preview.show();
			loading.hide();
		});
	},

	// přidání externího obrázku
	imageExternal: function (imageUrl) {
		this.insertAt(' [* ' + imageUrl + ' *] ');
	},

	// přidání odkazu
	link: function (url, anchor) {
		var selection = this.text.getSelection();
		var link = '';
		url = jQuery.trim(url);
		anchor = jQuery.trim(anchor);

		if (url && anchor) {
			link = ' "' + anchor + '":' + url + ' ';
		}
		else if (url) {
			link = ' ' + url + ' ';
		}
		else { // není zadána URL adresa
			return false;
		}

		this.replaceWith(link);

		return true;
	},

	// nahrazení vybraného textu vybranýn textem
	replaceWith: function(replacement) {
		var selection = this.text.getSelection();
		
		if (selection.length > 0) {
			this.text.replaceSelection(replacement);
		}
		else {
			this.insertAt(replacement);
		}
	},

	// nahrazení vybraného textu vybranýn textem a přidání něčeho před a něčeho po
	replaceWithPrePost: function(pre, post) {
		var selection = this.text.getSelection();
		var text = jQuery.trim(selection.text);

		if (text.length) {
			this.replaceWith(pre + text + post);
		}
		else { // není nic vybráno
			this.replaceWith(pre + post);
			this.text.setCaretPos((selection.start + pre.length + 1));
		}
	},

	// vložení textu na pozici kurzoru
	insertAt: function(string) {
		var selection = this.text.getSelection();			
		this.text.insertAtCaretPos(string);
		this.text.setCaretPos((selection.start + string.length + 1));
	},

	// vytvoří seznam - číslovaný (type == "ol"), s odrážkami (type == "ul"), blockquote (type == "bq")
	replaceWithList: function(type) {
		var selection = this.text.getSelection();
		var lines = selection.text.split(this.getLineDelimiter());			
		var lineCount = selection.length ? lines.length : 3;
		var replacement = '';
		
		for (var i = 1; i <= lineCount; ++i) {
			if (type === 'ul') { // nahrazuji necislovane seznamy
				replacement += '- ';
			} 
			else if (type === 'ol') { // nahrazuji cislovane seznamy
				replacement += i+') ';
			}
			if (selection.length) {
				replacement += lines[i - 1];
			}
			if (i !== lineCount) {
				replacement += this.getLineDelimiter();
			}
		}
		
		this.replaceWith(replacement);
	},

	// vrať oddělovač řádků
	getLineDelimiter: function() {
		if (this.lineDelimiter)return this.lineDelimiter;

		var unix = this.text.val().indexOf('\n');
		var mac = this.text.val().indexOf('\r');
		var win = this.text.val().indexOf('\r\n');
			
		if (unix >= 0) {
			this.lineDelimiter = '\n';
		}
		if (mac >= 0) {
			this.lineDelimiter = '\r';
		}
		if (win >= 0) {
			this.lineDelimiter = '\r\n';
		}
			
		if (unix >= 0 || mac >= 0 || win >= 0)return this.lineDelimiter;
			
		// jinak nastavím dle prohlížeče
		// ie -> windows
		if (document.selection) {
			this.lineDelimiter = '\r\n';
		// FF -> unix
		} else {
			this.lineDelimiter = '\n';
		}

		return this.lineDelimiter;
	},

	table: function (cols, rows, header) {
		if (cols < 1) {
			alert('Nezadali jste počet sloupců tabulky');
			return false;
		}
		if (rows < 1) {
			alert('Nezadali jste počet sloupců tabulky');
			return false;
		}
		
		var table = '';

		if (header === 'n')rows++;
		if (header === 'l')cols++;
		
		for (var i = 0; i < rows; ++i) {
			// Hlavička nahoře
			if (header === 'n' && i < 2) {
				table += '|';
				for (var j = 0; j < cols; ++j) {
					table += '--------';
				}
				table += this.getLineDelimiter();
			}
			
			// Buňky
			for (j = 0; j < cols; ++j) {
				// Hlavička vlevo
				if (header === 'l' && j === 0) {
					table += "|* \t";
					
				// Buňka bez hlavičky
				} else {
					table += "| \t"; 
				}
				if (i === 0 && j === 0) {
					var firstLength = table.length - 1;
				}
			}
			table += '|' + this.getLineDelimiter();
		}
		table += this.getLineDelimiter();
		
		this.insertAt(table);

		return true;
	}
}

var ImageUploader = function(params) {
	this.params = params;
	
	u = new plupload.Uploader({
		runtimes : 'html5,flash,silverlight,gears,browserplus',
		required_features: 'multi_selection,progress,multipart',
		url : this.params.url,
		max_file_size : '10mb',
		filters : [
		           {title : "Obrázky nebo fotky", extensions : "jpg,jpeg,JPG,JPEG,gif,GIF,png,PNG,gif,GIF,bmp,BMP"}
		],
		flash_swf_url : '/plupload/plupload.flash.swf',
		silverlight_xap_url : '/plupload/plupload.silverlight.xap',		
		browse_button : this.params.buttonSelect,
		multipart : true,		
		container : this.params.container,
		multipart_params : this.params.data
	});
	u.params = this.params; // abych se na prametry dostal vždy také z uploderu, který se přidává do eventů
};

/**
 * Image Uploader využívající plUpload
 */
ImageUploader.prototype = {
	refresh: function () {
		u.refresh();
	},
		
	init: function() {
		// po nahrání fotky na server
		u.bind('FileUploaded', this.fileUploaded);
		
		// při uploadu změna nahrávání
		u.bind('UploadProgress', this.uploadProgress);
		
		// po vybrání souborů
		u.bind('FilesAdded', this.addFiles);
		
		// pokud se objeví error při incializaci
		u.bind('Error', this.errorInicialize);
		
		// inicialiace
		u.init();
		
		// standardní errory
		u.unbind("Error", this.errorInicialize);
		u.bind('Error', this.error);
	},

	addFiles: function (up, files) {
		$.each(files, function(i, file) {
			$('#imageFormImageUpload').tmpl({id : file.id, name : ((file.name.length > 15) ? file.name.substr(0, 15) + '...' : file.name), size: plupload.formatSize(file.size), percent: 'Připravuji nahrávání'}).appendTo('#filelist');
		});		
		up.refresh(); // Reposition Flash/Silverlight
		setTimeout('u.start()', 100); // ihned po vybrání souborů začnu s uploadem, timer je nasaven kvůli Flashi - u toho není možné volat start() přímo
	},
	
	fileUploaded: function (uploader, file, response) {
		// získám objekt s daty o nahraném obrázku
		var image = jQuery.parseJSON(response.response);
		
		ImageUploader.prototype.addImage(image.id, image.name);
		
		// skryju informaci o nahrávaném obrázku
		$('#' + file.id).hide();
	},
	
	addImage: function (id, name){
		var imageId = 'imageId' + id;
		
		// přidám nahranou fotku do nahraných fotek
		$('#imageFormImageUploaded').tmpl({id : id}).appendTo('#images');
		
		input = $('#' + imageId + " input");		
		input.val(name);
		input.css('font-style', 'italic');
		if (!name)input.DefaultValue("Zde zadejte popis fotky");
		
		$('#' + imageId + " input").blur(function (e) {
			if ($(this).val() != 'Zde zadejte popis fotky')$.get($(this).attr('action') + $(this).attr('id') + '&name=' + $(this).val());
			$(this).css('font-style', 'italic');
			e.preventDefault();
		});
		
		$('#' + imageId + " input").click(function() {
		 	if($(this).val() == '')$(this).val('');
		 	$(this).css('font-style', 'normal');
		});
		
		// smazání fotky ve frontě
		$('#' + imageId + " a").click(function (e) {
			$.get($(this).attr('href') + $(this).attr('id'));
			$(this).parent().parent().fadeOut("slow");
			e.preventDefault();
		});
	},
	
	uploadProgress: function (up, file) {
		if (file.percent > 96) {
			$('#' + file.id + " b").html('Čekejte prosím, ukládám a zmenšuji fotku');
		}
		else {
			$('#' + file.id + " b").html(file.percent + '%');
			$('#' + file.id + " img").show().attr('height', 10).attr('width', (file.percent*4));
		}
	},
	
	error: function (up, err) {
		up.refresh(); // Reposition Flash/Silverlight
	},
	
	errorInicialize: function (up, err) {
		$('#' + this.params.uploader).hide(); // skryju uploader
		$('#' + this.params.standard).show(); // zobrazím standardní nahrávání
		up.refresh(); // Reposition Flash/Silverlight
	}
};

function reply(postId)
{
	$('#post_up_id').val(postId); // nastavím id příspěvku na který se reaguje
	
	// nastavím focus - tím se celé texterea překreslí neboť na získání focusu je nastavena událost
	$('#text').focus();
	
	if (location.href.match('#')) {
		var url = location.href.split('#');
		location.href = url[0] + '#form';
	}
	else {
		location.href = location.href + '#form';
	}
}

function cite(postId, domain)
{
	var returnValue = reply(postId);
	
	var clear = false;
	if ($('#text').val() == '') {
		$('#text').val('Načítám citovaný příspěvek, čekejte prosím ...');
		clear = true;
	}
	$.ajax({
	  url: 'http://' + domain + '?controller=Discussion&action=postforcite&postId=' + postId + '&ajax=1',
	  success: function(html){
	  	if (!clear) {
			html = $('#text').val() + "\n" + html;
		}
	  	html += "\n";
	    $('#text').val(html);
		$('#text').focus();
		
		// nastavím pozici kurzoru
		var selection = $('#text').getSelection();
		$('#text').setCaretPos((selection.start + html + 1));
	  }
	});
	
	return returnValue;
}

function citePm(pmId, domain)
{
	// posunu nahoru na formulář soukromé zprávy
	if (location.href.match('#')) {
		var url = location.href.split('#');
		location.href = url[0] + '#pmFormAnchor';
	}
	else {
		location.href = location.href + '#pmFormAnchor';
	}
	
	var clear = false;
	if ($('#text').val() == '') {
		$('#text').val('Načítám citovanou soukromou zprávu, čekejte prosím ...');
		clear = true;
	}
	$.ajax({
	  url: 'http://' + domain + '?controller=Community&action=pmforcite&pmId=' + pmId,
	  success: function(html){
	  	if (!clear) {
			html = $('#text').val() + "\n" + html;
		}
	    $('#text').val(html + "\n");
		$('#text').focus();
		
		// nastavím pozici kurzoru
		var selection = $('#text').getSelection();
		$('#text').setCaretPos((selection.start + html + 1));
	  }
	});
	
	return false;
}

// mini diskusní příspěvky

var msgWrite = 'Napište příspěvek ...';
var msgSending = '<span class="comment_ajaxloading">Odesílám příspěvek, čekejte prosím</span>';
var msgLoading = '<span class="comment_ajaxloading">Načítám příspěvky, čekejte prosím</span>';

function loadMiniPosts(domain, typeId, id, addText, addUserName, addUserEmail)
{
	$('#postMiniForm' + id).hide();
	
	var postData = {
		typeId: typeId, 
		topicId: id,
		controller: 'Ajax', 
		action: 'discussionposts', 
		ajax: 'true'
	};
	
	if (addText && addText.trim()){ // chci navíc přidat nový příspěvek
		$('#postMiniPosts' + id).html(msgSending);
		
		postData.text = addText;
		postData.form_hSystem_Core_Discussion_Post_1 = 'form_hSystem_Core_Discussion_Post_1';
		postData.user_name = addUserName;
		postData.user_email = addUserEmail;
		postData.as_code = 'WEBDIO';
		postData.notification = 1;
		
		// v případě zakládání nového tématu
		if ($('#postMiniFormTitle'))postData.title = $('#postMiniFormTitle').val();
		if ($('#postMiniFormCategoryId'))postData.category_id = $('#postMiniFormCategoryId').val();
		if ($('#postMiniFormCategoryId1'))postData.category_id1 = $('#postMiniFormCategoryId1').val();
		if ($('#postMiniFormCategoryId2'))postData.category_id2 = $('#postMiniFormCategoryId2').val();
		if ($('#postMiniFormCategoryId3'))postData.category_id3 = $('#postMiniFormCategoryId3').val();
		if ($('#postMiniFormCategoryId4'))postData.category_id4 = $('#postMiniFormCategoryId4').val();
	}
	else {
		$('#postMiniPosts' + id).html(msgLoading);
	}
	domain = 'http://' + domain + 'ajax/';
	
	$.post(
		domain, 
		postData,
		function(data){	
			$('#postMiniPosts' + id).html(data.html);
			$('#postMiniPosts' + id).fadeIn();
			$('#postMiniForm' + id).fadeIn();
			$('#postMiniShowAll' + id).hide();
			
			if (data.postAddedId > 0) {
				if (id == -1) {
					location.href = location.href + '#postsMini';
					location.reload();
				}
				
				// skryji pole a vrátím ho do původní grafické podoby
				textarea = $('#postMiniFormTextarea' + id);
				textarea.removeClass("postMiniTextareaBig"); 
				textarea.addClass("postMiniTextarea");
				textarea.val(msgWrite);
				
				$('#postMiniFormIcon' + id).hide();
				$('#postMiniFormSubmit' + id).hide();
			}
		},
		'json'
	);
}

function postMiniPost(domain, typeId, id, login)
{
	if (!login) {
		var userName = $('#postMiniFormUserName' + id).val().trim();
		var userEmail = $('#postMiniFormUserEmail' + id).val().trim();
		
		if ((!userName) || (!userEmail)) {
			alert('Zadejte jméno a e-mail (nebude se zobrazovat)');
			return false;
		}
	}
	else {
		var userName = '';
		var userEmail = '';
	}
	
	text = $('#postMiniFormTextarea' + id).val();
	if (!text.trim()) {
		alert('Zadejte text příspěvku');
		return false;
	}
	
	// zavolám zobrazení příspěvků s přidáním dalšího textu
	loadMiniPosts(domain, typeId, id, text.trim(), userName, userEmail);
}

function writeMiniPost(domainMainWww, id)
{	
	textarea = $('#postMiniFormTextarea' + id);
	textarea.removeClass("postMiniTextarea"); 
	textarea.addClass("postMiniTextareaBig");
	
	if (textarea.val() == msgWrite) {
		textarea.val('');
	}
	
	if ($('#postMiniFormUser' + id))$('#postMiniFormUser' + id).show();
	$('#postMiniFormIcon' + id).show();
	$('#postMiniFormSubmit' + id).show();
}

// end mini diskusní příspěvky
