/*! Copyright (c) 2008 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Version: 1.0.3
 * Requires jQuery 1.1.3+
 * Docs: http://docs.jquery.com/Plugins/livequery
 */

(function($) {

	$.extend($.fn, {
		livequery: function(type, fn, fn2) {
			var self = this, q;

			// Handle different call patterns
			if ($.isFunction(type))
				fn2 = fn, fn = type, type = undefined;

			// See if Live Query already exists
			$.each( $.livequery.queries, function(i, query) {
				if ( self.selector == query.selector && self.context == query.context &&
					type == query.type && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid) )
					// Found the query, exit the each loop
					return (q = query) && false;
			});

			// Create new Live Query if it wasn't found
			q = q || new $.livequery(this.selector, this.context, type, fn, fn2);

			// Make sure it is running
			q.stopped = false;

			// Run it immediately for the first time
			q.run();

			// Contnue the chain
			return this;
		},

		expire: function(type, fn, fn2) {
			var self = this;

			// Handle different call patterns
			if ($.isFunction(type))
				fn2 = fn, fn = type, type = undefined;

			// Find the Live Query based on arguments and stop it
			$.each( $.livequery.queries, function(i, query) {
				if ( self.selector == query.selector && self.context == query.context &&
					(!type || type == query.type) && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid) && !this.stopped )
					$.livequery.stop(query.id);
			});

			// Continue the chain
			return this;
		}
	});

	$.livequery = function(selector, context, type, fn, fn2) {
		this.selector = selector;
		this.context  = context || document;
		this.type     = type;
		this.fn       = fn;
		this.fn2      = fn2;
		this.elements = [];
		this.stopped  = false;

		// The id is the index of the Live Query in $.livequery.queries
		this.id = $.livequery.queries.push(this)-1;

		// Mark the functions for matching later on
		fn.$lqguid = fn.$lqguid || $.livequery.guid++;
		if (fn2) fn2.$lqguid = fn2.$lqguid || $.livequery.guid++;

		// Return the Live Query
		return this;
	};

	$.livequery.prototype = {
		stop: function() {
			var query = this;

			if ( this.type )
				// Unbind all bound events
				this.elements.unbind(this.type, this.fn);
			else if (this.fn2)
				// Call the second function for all matched elements
				this.elements.each(function(i, el) {
					query.fn2.apply(el);
				});

			// Clear out matched elements
			this.elements = [];

			// Stop the Live Query from running until restarted
			this.stopped = true;
		},

		run: function() {
			// Short-circuit if stopped
			if ( this.stopped ) return;
			var query = this;

			var oEls = this.elements,
			els  = $(this.selector, this.context),
			nEls = els.not(oEls);

			// Set elements to the latest set of matched elements
			this.elements = els;

			if (this.type) {
				// Bind events to newly matched elements
				nEls.bind(this.type, this.fn);

				// Unbind events to elements no longer matched
				if (oEls.length > 0)
					$.each(oEls, function(i, el) {
						if ( $.inArray(el, els) < 0 )
							$.event.remove(el, query.type, query.fn);
					});
			}
			else {
				// Call the first function for newly matched elements
				nEls.each(function() {
					query.fn.apply(this);
				});

				// Call the second function for elements no longer matched
				if ( this.fn2 && oEls.length > 0 )
					$.each(oEls, function(i, el) {
						if ( $.inArray(el, els) < 0 )
							query.fn2.apply(el);
					});
			}
		}
	};

	$.extend($.livequery, {
		guid: 0,
		queries: [],
		queue: [],
		running: false,
		timeout: null,

		checkQueue: function() {
			if ( $.livequery.running && $.livequery.queue.length ) {
				var length = $.livequery.queue.length;
				// Run each Live Query currently in the queue
				while ( length-- )
					$.livequery.queries[ $.livequery.queue.shift() ].run();
			}
		},

		pause: function() {
			// Don't run anymore Live Queries until restarted
			$.livequery.running = false;
		},

		play: function() {
			// Restart Live Queries
			$.livequery.running = true;
			// Request a run of the Live Queries
			$.livequery.run();
		},

		registerPlugin: function() {
			$.each( arguments, function(i,n) {
				// Short-circuit if the method doesn't exist
				if (!$.fn[n]) return;

				// Save a reference to the original method
				var old = $.fn[n];

				// Create a new method
				$.fn[n] = function() {
					// Call the original method
					var r = old.apply(this, arguments);

					// Request a run of the Live Queries
					$.livequery.run();

					// Return the original methods result
					return r;
				}
			});
		},

		run: function(id) {
			if (id != undefined) {
				// Put the particular Live Query in the queue if it doesn't already exist
				if ( $.inArray(id, $.livequery.queue) < 0 )
					$.livequery.queue.push( id );
			}
			else
				// Put each Live Query in the queue if it doesn't already exist
				$.each( $.livequery.queries, function(id) {
					if ( $.inArray(id, $.livequery.queue) < 0 )
						$.livequery.queue.push( id );
				});

			// Clear timeout if it already exists
			if ($.livequery.timeout) clearTimeout($.livequery.timeout);
			// Create a timeout to check the queue and actually run the Live Queries
			$.livequery.timeout = setTimeout($.livequery.checkQueue, 20);
		},

		stop: function(id) {
			if (id != undefined)
				// Stop are particular Live Query
				$.livequery.queries[ id ].stop();
			else
				// Stop all Live Queries
				$.each( $.livequery.queries, function(id) {
					$.livequery.queries[ id ].stop();
				});
		}
	});

	// Register core DOM manipulation methods
	$.livequery.registerPlugin('append', 'prepend', 'after', 'before', 'wrap', 'attr', 'removeAttr', 'addClass', 'removeClass', 'toggleClass', 'empty', 'remove');

	// Run Live Queries when the Document is ready
	$(function() {
		$.livequery.play();
	});


	// Save a reference to the original init method
	var init = $.prototype.init;

	// Create a new init method that exposes two new properties: selector and context
	$.prototype.init = function(a,c) {
		// Call the original init and save the result
		var r = init.apply(this, arguments);

		// Copy over properties if they exist already
		if (a && a.selector)
			r.context = a.context, r.selector = a.selector;

		// Set properties
		if ( typeof a == 'string' )
			r.context = c || document, r.selector = a;

		// Return the result
		return r;
	};

	// Give the init function the jQuery prototype for later instantiation (needed after Rev 4091)
	$.prototype.init.prototype = $.prototype;

})(jQuery);//part of Live Form Validation plugin for Nette Framework
//JavaScript functions for custom rendering of client-side errors
//change to your satisfaction (you can use 3rd party JS libs)

function hasClass(ele, cls) {
    var classes = ele.className.split(" ");
    for (var i=0;i<classes.length;i++)
        if (classes[i].indexOf(cls) == 0)
            return true;
    return false;
}
function addClass(ele,cls) {
	if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
	if (hasClass(ele,cls)) {
		var classes = ele.className.split(" ");
        ele.className = '';
        i = 0;
        for (var i=0;i<classes.length;i++)
            if (classes[i].indexOf(cls) != 0)
            {
                if(i==0) ele.className += classes[i];
                else ele.className += ' '+classes[i];
                i++;
            }
	}
}
function errorMessageElement(id, sender, messageBox)
{
    var el = document.getElementById(id);
    if(!el)
    {
        el = document.createElement('span');
        el.id = id;
        var parent = sender.parentNode;
        var messageBoxEl = null;
        if (messageBox)
            messageBoxEl = document.getElementById(messageBox);
        if (messageBoxEl) {
            messageBoxEl.appendChild(el);
        } else if(parent.lastchild == sender) {
            parent.appendChild(el);
        } else {
            parent.insertBefore(el, sender.nextSibling);
        }
    }
    else
    {
        el.style.display = 'inline';
    }
    return el;
}
function addError(sender, message, messageBox)
{
    addClass(sender, 'form-control-error');
    var id = sender.id+'_message';
    el = errorMessageElement(id, sender, messageBox);
    el.className = 'form-error-message';
    el.innerHTML = message;
}
function removeError(sender)
{
    removeClass(sender, 'form-control-error');
    var el = document.getElementById(sender.id+'_message');
    if(el)
        el.style.display = 'none';
    onValid(sender);
}
function informError(submitter)
{
    el = errorMessageElement(submitter.id+"_message", submitter);
    el.className = "form-error-message";
    el.innerHTML = "\u0160patn\u011b vypln\u011bný formulá\u0159!"
}
function onValid(sender)
{
    var id = sender.id+'_message';
    el = errorMessageElement(id, sender);
    el.className = 'form-valid-message';
    el.innerHTML = "";
}
/**
 * AJAX Nette Framwork plugin for jQuery
 *
 * @copyright   Copyright (c) 2009 Jan Marek
 * @license     MIT
 * @link        http://nettephp.com/cs/extras/jquery-ajax
 * @version     0.2
 */

/**
 * Common AJAX setup
 */
jQuery.extend({
	nette: {
		updateSnippet: function (id, html) {
                        el = document.getElementById(id);
                        //$(el).html(html);
                        $("#"+id).html(html);
                        /*$("#" + id).fadeTo("fast", 0.4, function () {
				$(this).html(html).fadeTo("fast", 1);
				$.nette.registerAfterUpdate();
			});*/
		},

                updateInnerSnippet: function (id, html) {
			$("#" + id).parent().html(html);
                        /*$("#" + id).fadeTo("fast", 0.4, function () {
				$(this).html(html).fadeTo("fast", 1);
				$.nette.registerAfterUpdate();
			});*/
		},

		success: function (payload) {
			// redirect
			if (payload.redirect) {
				window.location.href = payload.redirect;
				return;
			}

			// snippets
			if (payload.snippets) {
				for (var i in payload.snippets) {
					jQuery.nette.updateSnippet(i, payload.snippets[i]);
				}
			}

                        // inner snippets
			if (payload.innerSnippets) {
				for (var i in payload.innerSnippets) {
					jQuery.nette.updateInnerSnippet(i, payload.innerSnippets[i]);
				}
			}

                        // opětovná inicializace
                        //netteAjaxInit();
                        //datagridAjaxInit();
                        //initTinyMCE();

		},

                registerAfterUpdate: function() { }
	}
});

jQuery.ajaxSetup({
	success: jQuery.nette.success,
	dataType: "json"
});

// skrývání flash zpráviček
$("div.flash").livequery(function () {
	var el = $(this);
	setTimeout(function () {
		el.animate({"opacity": 0}, 2000);
		el.slideUp();
	}, 7000);
});/**
 * AJAX form plugin for jQuery
 *
 * @copyright  Copyright (c) 2009 Jan Kuchař, Copyright (c) 2009 Jan Marek
 * @license    MIT
 * @link       http://addons.nettephp.com/cs/ajax-form-s-eventy
 * @version    0.1
 */

jQuery.fn.extend({
    ajaxSubmit: function (e,callback) {
        var form;
        var sendValues = {};

        // submit button
        if (this.is(":submit")) {
            form = this.parents("form");
            // we will prevent ajax processing in the future (i.e. for file uploads)
            if (this.hasClass('noajax')) { 
                form.data("noAjaxSubmitCalled",true);
                return null;
            }
            sendValues[this.attr("name")] = this.val() || "";

        // form
        } else if (this.is("form")) {
            form = this;
            if (form.data("noAjaxSubmitCalled")==true) {
                return null;
            }

        // invalid element, do nothing
        } else {
            return null;
        }

        // Vynecháme výchozí akci prohlížeče
        if (e != null && e.preventDefault) e.preventDefault();

        // validation
        if (form.get(0).onsubmit && !form.get(0).onsubmit()) {
            // Zastavíme vykonávání jakýchkoli dalších eventů
            if (e != null && e.stopImmediatePropagation) e.stopImmediatePropagation();
            return null;
        }

        // Abychom formulář neodeslali zbytečně vícekrát
        if(form.data("ajaxSubmitCalled")==true)
            return null;

        form.data("ajaxSubmitCalled",true);

        // Tím, že zaregistruji ajaxové odeslání až teď, tak se provede jako poslední. (až po všech ostatních)
        form.one("submit",function(){
            // get values
            var values = form.serializeArray();

            for (var i = 0; i < values.length; i++) {
                var name = values[i].name;

                // multi
                if (name in sendValues) {
                    var val = sendValues[name];

                    if (!(val instanceof Array)) {
                        val = [val];
                    }

                    val.push(values[i].value);
                    sendValues[name] = val;
                } else {
                    sendValues[name] = values[i].value;
                }
            }

            // send ajax request
            var ajaxOptions = {
                url: form.attr("action"),
                data: sendValues,
                type: form.attr("method") || "get"
            };

            ajaxOptions.complete = function(){
                form.data("ajaxSubmitCalled",false);
            }

            if (callback) {
                ajaxOptions.success = callback;
            }
            return jQuery.ajax(ajaxOptions);
        })

        if (e != null && e.stopImmediatePropagation) e.stopImmediatePropagation();
        form.submit();
        return false;

    }
});


function netteAjaxInit() {

    $("form.ajax").livequery("submit",function (e) {
        $(this).ajaxSubmit(e);
    });

    $("form.ajax :submit").livequery("click",function (e) {
        $(this).ajaxSubmit(e);
    });

    $("input.ajax").livequery("click",function (e) {
        $(this).ajaxSubmit(e);
    });

    $("a.ajax").live("click", function () {
	$.get(this.href);
	return false;
    });

}/**
 * JQuery rozšíření.
 *
 * RAPIDLIME s.r.o.
 * 
 * Autor: Jiri Musil
 */

jQuery.fn.extend({

    loadAfter: function(url) {
        var $el = $(this);
        jQuery.get(url, {}, function(data) {
            $el.after(data);
        }, 'html');

    },

    /**
     * Jednoduché nahrazení atributu.
     */
    replaceAttr: function(aName, rxString, repString) {
        return this.attr(
            aName,
            function() {
                return jQuery(this).attr(aName).replace(rxString, repString);
            }
            );
    },



    /**
     * Provede toggle se slide effektem.
     */
    slideToggle: function() {
        if (this.is(":hidden")) {
            this.slideDown("slow");
        } else {
            this.slideUp("slow");
        }
    },



    /**
     * Projde strom checkboxu oprávnění (permElements) vytvořený při loadu stránky a dle
     * kliknutného prvku aktualizuje hodnoty ostatních. Zároveň strom přestyluje podle aktuálního
     * nastavení.
     */
    updatePermissionsCheckboxes: function (permElements) {
        el = $(this);
        elId = el.attr('id');
        checked = el.attr('checked');
        
        if (elId == 'root') { // root clicked

            children = permElements[0]['children'];
            for (c in children) {

                resource = children[c]['element'];
                resource.attr('checked', checked);
                resource.attr('class', checked ? 'allSelected' : '');

                for (cc in children[c]['children']) {

                    scope = children[c]['children'][cc]['element'];
                    scope.attr('checked', checked);
                    scope.attr('class', checked ? 'allSelected' : '');

                    for (ccc in children[c]['children'][cc]['children']) {
                        priv = children[c]['children'][cc]['children'][ccc]['element'];
                        priv.attr('checked', checked);
                    }

                }
            }

        } else {

            elName = elId.split('-')[1];
            elNameParts = elName.split('_');

            if (elNameParts.length == 1) { // resource clicked

                children = permElements[0]['children']['perm_cb-'+elName]['children'];
                for (c in children) {
                    scope = children[c]['element'];
                    scope.attr('checked', checked);
                    for (cc in children[c]['children']) {
                        priv = children[c]['children'][cc]['element'];
                        priv.attr('checked', checked);
                    }
                }

            } else if (elNameParts.length == 2) { // scope clicked

                children = permElements[0]['children']['perm_cb-'+elNameParts[0]]['children']['perm_cb-'+elName]['children'];
                for (c in children) {
                    priv = children[c]['element'];
                    priv.attr('checked', checked);
                }

            } // else if (elNameParts.length == 3) {} // privilege clicked

        }

        jQuery.apcentrum.setCheckboxesStates(permElements);

    },



    /**
     * Nastyluje daný checkbox a další elementy dle parametrů.
     */
    setCheckboxState: function(c, u) {
        el = $(this);
        label = $("label[for='"+el.attr('id')+"']");
        if (c && u) cl = 'notAllSelected';
        else if (c && !u)  cl = 'allSelected';
        else cl = '';
        label.attr('class', cl);
        el.attr('checked', c);
    },



    inactivateLink: function() {
        //html = this.html();
        //this.replaceWith('<a href="#" click="return false;">' + html + '</a>');
        this.attr('href','');
        this.livequery('click', function(event) {
            event.stopImmediatePropagation();
        });
    },

    restoreScroll: function(){
        var strCook = document.cookie;
        if(strCook.indexOf("!~")!=0){
            var intS = strCook.indexOf("!~");
            var intE = strCook.indexOf("~!");
            var strPos = strCook.substring(intS+2,intE);
            this.scrollTop = strPos;
        }
    },

    saveScroll: function(){
        var intY = this.scrollTop;
        document.cookie = "yPos=!~" + intY + "~!";
    },

    toggleClass: function(wrapId) {
        wrapEl = jQuery(wrapId);
        if (wrapEl.is(":hidden")) {
            wrapEl.slideDown("slow");
            this.addClass('wrapShown');
            this.removeClass('wrapHidden');
        } else {
            wrapEl.slideUp("slow");
            this.removeClass('wrapShown');
            this.addClass('wrapHidden');
        }
        return false;
    }


});

jQuery.extend({

    apcentrum: {



        /**
         * Nastaví CSS třídy checkboxům (a dalším elementům) v PermissionControl komponentě.
         */
        setCheckboxesStates: function (permElements) {
                    
            children = permElements[0]['children'];
            c_c = false;
            c_u = false;

            for (c in children) {

                resource = children[c]['element'];
                cc_c = false;
                cc_u = false;

                for (cc in children[c]['children']) {

                    scope = children[c]['children'][cc]['element'];
                    ccc_c = false;
                    ccc_u = false;

                    for (ccc in children[c]['children'][cc]['children']) {

                        priv = children[c]['children'][cc]['children'][ccc]['element'];
                        if (priv.attr('checked')) {
                            ccc_c = true;
                            cc_c = true;
                            c_c = true;
                        } else {
                            ccc_u = true;
                            cc_u = true;
                            c_u = true;
                        }
                        if (ccc_c && ccc_u) break;

                    }

                    scope.setCheckboxState(ccc_c, ccc_u);

                }

                resource.setCheckboxState(cc_c, cc_u);
            }

            root = permElements[0]['element'];
            root.setCheckboxState(c_c, c_u);
                    
        }

                

    }
});/**
 * JS tools.
 *
 * Author: Jiri Musil
 *
 */

/**
 * count down close of flash messages top bar
 */
function flashMessageCloseCountdown() {
    var val = $("#flash-messages-countdown").text();
    $("#flash-messages-countdown").text(val - 1);
    if ((val - 1) > 0)
        setTimeout("flashMessageCloseCountdown();", 1000);
}

/**
 * set the radio button with the given value as being checked
 * do nothing if there are no radio buttons
 * if the given value does not exist, all the radio buttons
 * are reset to unchecked
 */
function setCheckedValue(radioObj, newValue) {
    if(!radioObj)
        return;
    var radioLength = radioObj.length;
    if(radioLength == undefined) {
        radioObj.checked = (radioObj.value == newValue.toString());
        return;
    }
    for(var i = 0; i < radioLength; i++) {
        radioObj[i].checked = false;
        if(radioObj[i].value == newValue.toString()) {
            radioObj[i].checked = true;
        }
    }
}

/**
 * round to 2 decimals
 */
function round2(value) {
    return Math.round(value * 100)/100;
}
  

/**
 * Init of tinyMCE JS editor.
 */
function initTinyMCE() {
    tinyMCE.init({
            // General options
            mode : "specific_textareas",
            editor_selector : "mceEditor",
            theme : "advanced",
            plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,imagemanager,filemanager",

            // Theme options
            //theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
            theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect",
            theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,removeformat,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
            //theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
            theme_advanced_buttons3 : "",
            //theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
            theme_advanced_buttons4 : "",
            theme_advanced_toolbar_location : "top",
            theme_advanced_toolbar_align : "left",
            //theme_advanced_statusbar_location : "bottom",
            theme_advanced_statusbar_location : "bottom",
            theme_advanced_resizing : true,
            theme_advanced_path : false,
            theme_advanced_blockformats : "p,div,h1,h2,h3,h4,h5,h6,blockquote,code",

            // Example content CSS (should be your site CSS)
            //content_css : "css/example.css",

            // Drop lists for link/image/media/template dialogs
            template_external_list_url : "js/template_list.js",
            external_link_list_url : "js/link_list.js",
            external_image_list_url : "js/image_list.js",
            media_external_list_url : "js/media_list.js",

            // Replace values for the template plugin
            template_replace_values : {
                    username : "Some User",
                    staffid : "991234"
            }
    });
}

jQuery(document).ready(function () {
    // antiSpam
    $('a.m').each(function() {
        parts = $(this).html().split('/');
        email = parts[0] + '@' + parts[1] + '.' + parts[2];
        $(this).html(email)
            .attr('href', 'mailto:' + email)
            .attr('title', 'Poslat e-mail ' + email);
    });

    $('#newsletter-subscribe a:last').click(function() {
        $('#newsletter-wrapper').slideUp();
        $.cookie('newsletter-subscribe-close', true, {expires: 7, path: '/'});
        return false;
    });

    $('form[name=frm-editForm]').submit(function() {
        if ($('select', $(this)).val() == 'PAID')
            return confirm('Opravdu si přejete potvrdit objednávku?');
        return true;
    });

    $('form[name=frm-mergeForm]').submit(function() {
        if ($('input[name=email]', $(this)).val() != '') {
            return confirm('Opravdu si přejete spojit uživatele?');
        }
        return true;
    });

    $('#frmdealForm-deal-supplier_id').change(function() {
        form = $(this).parent('form');
        if ($(this).val() == 0) {
            $('.supplierbox').show('slow');
        } else {
            $('.supplierbox').hide('slow');
        }
    });
    $('#frmdealForm-deal-supplier_id').change();

    $('input.datetimepicker').datepicker({
        duration: '',
        changeMonth: true,
        changeYear: true,
        yearRange: '2007:2020',
        showTime: true,
        time24h: true,
        currentText: 'Dnes',
        closeText: 'OK'
    });

    $('.importantPaymentInfoBox input').mouseenter(function() {
        $(this).select();
    })


    // --- Potvrzování -------------------------------------------------

    $('a[data-confirm]').live('click', function(event) {

            var q = $(this).attr('data-confirm');
            if (confirm(q)) {
                    return true;
            } else {
                    event.preventDefault();
            }

    });


});

Deal = {

	price : 0,

        itemPriceSelector : '',

        completePriceSelector : '',

        amountSelector : '',

        bonusSelector : '',

        bonusValueSelector : '',
		
		allowUseBonus: true,

	getCompletePrice : function(amount)
	{
            var noBonusPrice = this.price * amount;
            var bonus = Math.min(noBonusPrice, this.bonus);
        },

        updateCompletePrice : function() {
			var number = jQuery(this.amountSelector).val();
			
			var bonus = Deal.allowUseBonus ? jQuery(this.bonusValueSelector).val() : 0;

            var noBonusPrice = this.price * number;
            var finalPrice = noBonusPrice - bonus;
            var usedBonus = bonus;
            if (finalPrice <= 0) {
                usedBonus = noBonusPrice;
                finalPrice = 0;
                jQuery(this.cardPaymentSelector).hide();
                jQuery(this.bankTransferPaymentSelector).hide();
                jQuery(this.bonusPaymentSelector).show();
                jQuery(this.bonusRadioSelector).attr("checked", "checked");
                jQuery(this.bonusRadioSelector).hide();
            } else {
                jQuery(this.cardPaymentSelector).show();
				if (this.type == 'instant') {
                    jQuery(this.bankTransferPaymentSelector).hide();
                    jQuery(this.cardRadioSelector).attr("checked", "checked");
                    jQuery(this.cardRadioSelector).hide();
                    jQuery(this.brandboxSelector).show();
                } else {
                    if (jQuery(this.cardRadioSelector).attr("checked")) {
                        jQuery(this.brandboxSelector).show();
					} else {
                        jQuery(this.brandboxSelector).hide();
					}
                    jQuery(this.bankTransferPaymentSelector).show();
                }
                jQuery(this.bonusPaymentSelector).hide();
        }

            jQuery(this.bonusSelector).text(parseInt(usedBonus));
            jQuery(this.itemPriceSelector).text(parseInt(finalPrice));
            jQuery(this.completePriceSelector).text(parseInt(finalPrice));

            $('#deal-bonus').fadeOut('normal', function() {
                $(this).text(parseInt(dealBonus * number)).fadeIn('normal');
            });

			if (this.type != 'instant') {
				order_gift_card_update();
			}
        },

        showGiftEmail : function() {
            $('#giftBox').show();
            $('#frmamountForm-gift').val('1');
            return false;
        },

        hideGiftEmail : function() {
            $('#giftBox').hide();
            $('#frmamountForm-gift_email').val('');
            $('#frmamountForm-gift').val('0');
            return false;
        }

}


function order_gift_card_show(){
	order_gift_card_update();

	$('#itemPrice').addClass('smaller');
	$('#gift_card_baner_link').css('display', 'none');
	$('#div_order_gitfcard').css('display', 'block');

	bind_order_gift_card_update();

	return false;
}


function bind_order_gift_card_update(){
	$('#frmnewOrderForm-giftCardValue').bind('change click focus blur mousewheel keyup', function() {order_gift_card_update()} );
}

function order_gift_card_hide() {
	$('#itemPrice').removeClass('smaller');
	$('#gift_card_baner_link').css('display', 'block');
	$('#div_order_gitfcard').css('display', 'none');
	$('#frmnewOrderForm-giftCardValue').val('0');
	order_gift_card_update();
	return false;
}

function order_gift_card_update(){
	price = parseInt( $('#itemPrice').html() );
	price += parseInt( $('#frmnewOrderForm-giftCardValue option:selected').val() );
	$('#gift_card_total').html( price );
	if(price > 0) {
		$(Deal.cardPaymentSelector).show();
		$(Deal.bankTransferPaymentSelector).show();
		$(Deal.bonusPaymentSelector).hide();
	} else {
		$(Deal.cardPaymentSelector).hide();
		$(Deal.bankTransferPaymentSelector).hide();
		$(Deal.bonusPaymentSelector).show();
	}


}//SETTING UP OUR POPUP
//0 means disabled; 1 means enabled;
var popupStatus = 0;

//loading popup with jQuery magic!
function loadPopup(){
    //loads popup only if it is disabled
    if(popupStatus==0){
    $("#backgroundPopup").css({
        "opacity": "0.7"
    });
    $("#backgroundPopup").fadeIn();
    $("#popupContact").fadeIn();
    popupStatus = 1;
    }
}

//disabling popup with jQuery magic!
function disablePopup(){
    //disables popup only if it is enabled
    if(popupStatus==1){
    $("#backgroundPopup").fadeOut();
    $("#popupContact").fadeOut();
    popupStatus = 0;
    }
}

//centering popup
function centerPopup(){

    //request data for centering
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    var popupHeight = $("#popupContact").height();
    var popupWidth = $("#popupContact").width();
    //centering
    $("#popupContact").css({
    "position": "absolute",
    "top": jQuery(document).scrollTop()+windowHeight/2-popupHeight/2,
    "left": windowWidth/2-popupWidth/2
    });
    //only need force for IE6

    $("#backgroundPopup").css({
        "height": windowHeight
    });

}

$(document).ready(function(){

    //CLOSING POPUP
    //Click the x event!
    $("#popupContactClose").click(function(){
        disablePopup();
    });

    //Click out event!
    $("#backgroundPopup").click(function(){
        disablePopup();
    });

    //Press Escape event!
    $(document).keypress(function(e){
        if(e.keyCode==27 && popupStatus==1){
            disablePopup();
        }
    });

});

﻿/**
 * jQuery.timers - Timer abstractions for jQuery
 * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2009/10/16
 *
 * @author Blair Mitchelmore
 * @version 1.2
 *
 **/

jQuery.fn.extend({
	everyTime: function(interval, label, fn, times) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.extend({
	timer: {
		global: [],
		guid: 1,
		dataKey: "jQuery.timer",
		regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseFloat(result[1]);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times) {
			var counter = 0;
			
			if (jQuery.isFunction(label)) {
				if (!times) 
					times = fn;
				fn = label;
				label = interval;
			}
			
			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval < 0)
				return;

			if (typeof times != 'number' || isNaN(times) || times < 0) 
				times = 0;
			
			times = times || 0;
			
			var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});
			
			if (!timers[label])
				timers[label] = {};
			
			fn.timerID = fn.timerID || this.guid++;
			
			var handler = function() {
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
			};
			
			handler.timerID = fn.timerID;
			
			if (!timers[label][fn.timerID])
				timers[label][fn.timerID] = window.setInterval(handler,interval);
			
			this.global.push( element );
			
		},
		remove: function(element, label, fn) {
			var timers = jQuery.data(element, this.dataKey), ret;
			
			if ( timers ) {
				
				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.timerID ) {
							window.clearInterval(timers[label][fn.timerID]);
							delete timers[label][fn.timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}
					
					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}
				
				for ( ret in timers ) break;
				if ( !ret ) 
					jQuery.removeData(element, this.dataKey);
			}
		}
	}
});

jQuery(window).bind("unload", function() {
	jQuery.each(jQuery.timer.global, function(index, item) {
		jQuery.timer.remove(item);
	});
});
