/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 *
 * Open source under the BSD License.
 *
 * Copyright Â© 2008 George McGinley Smith
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list of
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list
 * of conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution.
 *
 * Neither the name of the author nor the names of contributors may be used to endorse
 * or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
    def: 'easeOutQuad',
    swing: function (x, t, b, c, d) {
        //alert(jQuery.easing.default);
        return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
    },
    easeInQuad: function (x, t, b, c, d) {
        return c*(t/=d)*t + b;
    },
    easeOutQuad: function (x, t, b, c, d) {
        return -c *(t/=d)*(t-2) + b;
    },
    easeInOutQuad: function (x, t, b, c, d) {
        if ((t/=d/2) < 1) return c/2*t*t + b;
        return -c/2 * ((--t)*(t-2) - 1) + b;
    },
    easeInCubic: function (x, t, b, c, d) {
        return c*(t/=d)*t*t + b;
    },
    easeOutCubic: function (x, t, b, c, d) {
        return c*((t=t/d-1)*t*t + 1) + b;
    },
    easeInOutCubic: function (x, t, b, c, d) {
        if ((t/=d/2) < 1) return c/2*t*t*t + b;
        return c/2*((t-=2)*t*t + 2) + b;
    },
    easeInQuart: function (x, t, b, c, d) {
        return c*(t/=d)*t*t*t + b;
    },
    easeOutQuart: function (x, t, b, c, d) {
        return -c * ((t=t/d-1)*t*t*t - 1) + b;
    },
    easeInOutQuart: function (x, t, b, c, d) {
        if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
        return -c/2 * ((t-=2)*t*t*t - 2) + b;
    },
    easeInQuint: function (x, t, b, c, d) {
        return c*(t/=d)*t*t*t*t + b;
    },
    easeOutQuint: function (x, t, b, c, d) {
        return c*((t=t/d-1)*t*t*t*t + 1) + b;
    },
    easeInOutQuint: function (x, t, b, c, d) {
        if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
        return c/2*((t-=2)*t*t*t*t + 2) + b;
    },
    easeInSine: function (x, t, b, c, d) {
        return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
    },
    easeOutSine: function (x, t, b, c, d) {
        return c * Math.sin(t/d * (Math.PI/2)) + b;
    },
    easeInOutSine: function (x, t, b, c, d) {
        return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
    },
    easeInExpo: function (x, t, b, c, d) {
        return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
    },
    easeOutExpo: function (x, t, b, c, d) {
        return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
    },
    easeInOutExpo: function (x, t, b, c, d) {
        if (t==0) return b;
        if (t==d) return b+c;
        if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
        return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
    },
    easeInCirc: function (x, t, b, c, d) {
        return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
    },
    easeOutCirc: function (x, t, b, c, d) {
        return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
    },
    easeInOutCirc: function (x, t, b, c, d) {
        if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
        return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
    },
    easeInElastic: function (x, t, b, c, d) {
        var s=1.70158;
        var p=0;
        var a=c;
        if (t==0) return b;
        if ((t/=d)==1) return b+c;
        if (!p) p=d*.3;
        if (a < Math.abs(c)) {
            a=c;
            var s=p/4;
        }
        else var s = p/(2*Math.PI) * Math.asin (c/a);
        return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
    },
    easeOutElastic: function (x, t, b, c, d) {
        var s=1.70158;
        var p=0;
        var a=c;
        if (t==0) return b;
        if ((t/=d)==1) return b+c;
        if (!p) p=d*.3;
        if (a < Math.abs(c)) {
            a=c;
            var s=p/4;
        }
        else var s = p/(2*Math.PI) * Math.asin (c/a);
        return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
    },
    easeInOutElastic: function (x, t, b, c, d) {
        var s=1.70158;
        var p=0;
        var a=c;
        if (t==0) return b;
        if ((t/=d/2)==2) return b+c;
        if (!p) p=d*(.3*1.5);
        if (a < Math.abs(c)) {
            a=c;
            var s=p/4;
        }
        else var s = p/(2*Math.PI) * Math.asin (c/a);
        if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
        return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
    },
    easeInBack: function (x, t, b, c, d, s) {
        if (s == undefined) s = 1.70158;
        return c*(t/=d)*t*((s+1)*t - s) + b;
    },
    easeOutBack: function (x, t, b, c, d, s) {
        if (s == undefined) s = 1.70158;
        return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
    },
    easeInOutBack: function (x, t, b, c, d, s) {
        if (s == undefined) s = 1.70158;
        if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
        return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
    },
    easeInBounce: function (x, t, b, c, d) {
        return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
    },
    easeOutBounce: function (x, t, b, c, d) {
        if ((t/=d) < (1/2.75)) {
            return c*(7.5625*t*t) + b;
        } else if (t < (2/2.75)) {
            return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
        } else if (t < (2.5/2.75)) {
            return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
        } else {
            return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
        }
    },
    easeInOutBounce: function (x, t, b, c, d) {
        if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
        return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
    }
});

/*
 *
 * TERMS OF USE - EASING EQUATIONS
 *
 * Open source under the BSD License.
 *
 * Copyright Â© 2001 Robert Penner
 * All rights reserved.
 *
 * Redistribution aneaseInOutCubicd use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list of
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list
 * of conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution.
 *
 * Neither the name of the author nor the names of contributors may be used to endorse
 * or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

/*
Copyright (c) 2009, Pim Jager
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* The name Pim Jager may not be used to endorse or promote products
derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY Pim Jager ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Pim Jager BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function($){
    //We use a small helper function that will return true when 'a' is undefined (so we can do if(checkUndefined(data)) return false;
    //If we would continue with undefined data we would piss javascript off as we would be getting properties of an
    //non-exsitent object (ie typeof data === 'undefined'; data.fooBar; //throws error
    var checkUndefined = function(a) {
        return typeof a === 'undefined';
    }
    $.expr[':'].data = function(elem, counter, params){
        if(checkUndefined(elem) || checkUndefined(params)) return false;
        //:data(__) accepts 'dataKey', 'dataKey=Value', 'dataKey.InnerdataKey', 'dataKey.InnerdataKey=Value'
        //Also instead of = we accept: != (does not equal Value), ^= (starts with Value),
        //		$= (ends with Value), *=Value (contains Value);
        //$(elem).data(dataKey) or $(elem).data(dataKey)[innerDataKey] (optional more innerDataKeys)
        //When no value is speciefied we return all elements that have the dataKey specified, similar to [attribute]
        var query = params[3]; //The part in the parenthesis, thus: selector:data( query )
        if(!query) return false; //query can not be anything that evaluates to false, it has to be string
        var querySplitted = query.split('='); //for dataKey=Value/dataKey.innerDataKey=Value
        //We check if the condition was an =, an !=, an $= or an *=
        var selectType = querySplitted[0].charAt( querySplitted[0].length-1 );
        if(selectType == '^' || selectType == '$' || selectType == '!' || selectType == '*'){
            querySplitted[0] = querySplitted[0].substring(0, querySplitted[0].length-1);
            //the ^=, *= and $= are only available when the $.stringQuery plugin is loaded, if it is not and any of these are used we return false
            if(!$.stringQuery && selectType != '!'){
                return false;
            }
        }
        else selectType = '=';
        var dataName = querySplitted[0]; //dataKey or dataKey.innerDataKey
        //Now we go check if we need dataKey or dataKey.innerDataKey
        var dataNameSplitted = dataName.split('.');
        var data = $(elem).data(dataNameSplitted[0]);
        if(checkUndefined(data)) return false;
        if(dataNameSplitted[1]){//We have innerDataKeys
            for(i=1, x=dataNameSplitted.length; i<x; i++){ //we start counting at 1 since we ignore the first value because that is the dataKey
                data = data[dataNameSplitted[i]];
                if(checkUndefined(data)) return false;
            }
        }
        if(querySplitted[1]){ //should the data be of a specified value?
            var checkAgainst = (data+'');
            //We cast to string as the query will always be a string, otherwise boolean comparison may fail
            //beacuse in javaScript true!='true' but (true+'')=='true'
            //We use this switch to check if we chould check for =, $=, ^=, !=, *=
            switch(selectType){
                case '=': //equals
                    return checkAgainst == querySplitted[1];
                    break;
                case '!': //does not equeal
                    return checkAgainst != querySplitted[1];
                    break;
                case '^': //starts with
                    return $.stringQuery.startsWith(checkAgainst, querySplitted[1]);
                    break;
                case '$': //ends with
                    return $.stringQuery.endsWith(checkAgainst, querySplitted[1]);
                    break;
                case '*': //contains
                    return $.stringQuery.contains(checkAgainst, querySplitted[1]);
                    break;
                default: //default should never happen
                    return false;
                    break;
            }
        }
        else{ //the data does not have to be a speciefied value
            //, just return true (we are here so the data is specified, otherwise false would have been returned by now)
            return true;
        }
    }
})(jQuery);

(function($) {

    $.extend({
        globals: {
            bubbles:{
                start:function(){},
                stop:function(){}
            },
            mouse: {
                x: 0,
                y: 0
            },

            window: {
                width: 0,
                height: 0,
                maxDist: 200
            }
        },

        initGlobalsHandler: function() {
            $(document).mousemove(function(e) {
                $.globals.mouse.x = e.pageX;
                $.globals.mouse.y = e.pageY;
            });

            $(window).resize(function(e) {
                $.globals.window.width = $(window).width();
                $.globals.window.height = $(window).height();

                /*if($('#container').width() > $(window).width()) {
                    $('body').css('overflowX', 'auto');
                } else {
                    $('body').css('overflowX', 'hidden');
                }

                if($('#container').height()+20 > $(window).height()) {
                    $('body').css('overflowY', 'auto');
                } else {
                    $('body').css('overflowY', 'hidden');
                }*/
            }).trigger('resize');
        }
    });

    $.fn.initForceSystem = function() {
        var $elements = $(this);
        var playing = false;

        $elements.each(function() {
            var $elm = $(this);
            $elm.data('width', $elm.width());
            $elm.data('height', $(this).height());

            $elm.data('parent', $elm.parent())

            $(window).resize(function() {
                $elm.data('offset', {
                    x: 	$elm.data('parent').offset().left,
                    y: 	$elm.data('parent').offset().top
                });
            }).trigger('resize');

            $elm.css({
                left: (Math.random() * $elm.data('parent').width()) - ($elm.width() / 2),
                top: (Math.random() * $elm.data('parent').height()) - ($elm.height() / 2)
            });

            $elm.data('nextUpdate', 1);
            $elm.data('orgLeft', $elm.position().left);
            $elm.data('orgTop', $elm.position().top);
        });

        var update = function() {
            $elements.each(function() {
                var $elm = $(this);
                var position = $elm.position();

                var maxDist = ($elm.width() * 20) + 1500;

                position = {
                    x: position.left,
                    y: position.top
                };

                var mouseDistance = {
                    x: (position.x + ($elm.data('width') / 2)) -  ($.globals.mouse.x - $elm.data('offset').x),
                    y: (position.y + ($elm.data('height') / 2)) -  ($.globals.mouse.y - $elm.data('offset').y)
                };

                var orgPosDistance = {
                    x: (position.x) - $elm.data('orgLeft'),
                    y: (position.y) - $elm.data('orgTop')
                };

                var totalMouseDistance = Math.sqrt(Math.pow(mouseDistance.x, 2) + Math.pow(mouseDistance.y, 2));

                var force = (totalMouseDistance / maxDist);

                var velX = ((mouseDistance.x) / totalMouseDistance / force) / 10;
                var velY = ((mouseDistance.y) / totalMouseDistance / force) / 10;

                velX -= orgPosDistance.x / 50;
                velY -= orgPosDistance.y / 50;

                $elm.css({
                    left: Math.ceil(position.x + velX),
                    top: Math.ceil(position.y + velY)
                });
            });
        }
        
        var interval = setInterval(update, 35);
        playing = true;

        $.globals.bubbles = {
            stop:function(){
                clearInterval(interval);
                playing = false;
            },
            start:function(){
                if(!playing){
                    interval = setInterval(update, 35);
                    playing = true;
                }
            }
        };
    }


    $.fn.selectBoxReplacement = function() {
        return $(this).each(function(){
            var $select = $(this);
            var replacement = $('<ul class="select-replacement"></ul>');
            var selectedItem = $('<li class="selected"><span class="selected-text"></span></li>').appendTo(replacement);
            var selectedText = selectedItem.find('.selected-text');
            var options = $('<div class="options"><ul></ul></div>').appendTo(selectedItem);
			
            $select.find('option').each(function() {
                var option = $(this);
                var li = $('<li>'+option.text()+'</li>');
                options.find('ul').append(li);
            });
			
            var liOptions = options.find('li');
			
            liOptions.click(function() {
                liOptions.removeClass('active');
                $(this).addClass('active');
                var index = options.find('li').index($(this));
                $select[0].selectedIndex = index;
                selectedText.text($(this).text());
            });

			
            replacement.click(function(){
                options.toggle();
            });
			
            $(document).click(function(e) {
                var t = e.target;
                if(!$(t).closest('.select-replacement').is('ul') && !$(t).closest('.input-row').find('.select-replacement').is('ul')) {
                    options.hide();
                }
            });
			
            selectedText.text(liOptions.eq($select[0].selectedIndex).addClass('active').text());
			
            options.hide();
            $select.hide();
            replacement.insertAfter($select);
        });
    }
	
	
    $.fn.checkboxReplacement = function() {
        return $(this).each(function() {
            var $check = $(this);
            var $label = $('label[for='+$check.attr('id')+']');
            var replacement = $('<div class="checkbox-replacement"></div>');
			
            var checkCheck = function() {
                if($check.is(':checked')) {
                    replacement.addClass('checked');
                } else {
                    replacement.removeClass('checked');
                }
            };
			
            $check.hide();
            
			replacement.click(function(){
                $check.trigger('click');
                checkCheck();
            });

            replacement.insertAfter($check);

            $label.click(function(e) {
                setTimeout(function() {
                	checkCheck();
                }, 20);
            });
			
            checkCheck();
        });
    }

    $.fn.setCursorPosition = function(start,stop) {
        if ($(this).get(0).setSelectionRange) {
            $(this).get(0).setSelectionRange(start, stop);
        } else if ($(this).get(0).createTextRange) {
            var range = $(this).get(0).createTextRange();
            range.collapse(true);
            range.moveEnd('character', stop);
            range.moveStart('character', start);
            range.select();
        }
    }

	
    $.fn.selectSearch = function(){
        return $(this).each(function(){
            var $select = $(this).hide();
            var $label = $(this).parent().find('label').show();
            var $input = $('<input id="'+$select.attr('id')+'" type="text" maxlength="30" class="text" name="" tabindex="'+$select.attr('tabindex')+'" />');
            var selected = $select.find('option:not(:first):selected').text();
            $select.attr('id','');

            $input.val(selected);
            $select.parent().append($input);

            var search = function(text){
                var reg = new RegExp("^"+text,'i');
                var match = -1;
                $select.find('option').each(function(i){
                    if($(this).text().search(reg) > -1){
                        if(match < 0){
                            match = i;
                        }
                    }
                });
                
                if(match > 0){
                    $select.find('option:eq('+match+')').attr('selected','selected');
                    $input.val($select.find('option:eq('+match+')').text());
                    $input.setCursorPosition(text.length, $input.val().length);
                }else{
                    $select.find('option').attr('selected','');
                }
            }

            $input.keyup(function(e){
                if ((e.keyCode >= 65 && e.keyCode <= 90) || e.keyCode == 192){
                    var text = $(this).val();
                    search(text);
                }
            });

            $input.change(function(e){
                e.preventDefault();
                var text = $(this).val();
                search(text);
            });
        });
    }
	
    $.fn.initUploadForm = function() {
        return $(this).each(function() {
            var $form = $(this);
            var $image = $form.find('input[type="file"]');
            var $error = $form.find('.error p');
            var $imageCrop = $form.find('#imageCrop');
            var $imageFit = $form.find('.image-fit');
            var $imageFitWrapper = $imageFit.find('.image-wrapper');
            var imageFitWrapperOffset = $imageFitWrapper.offset();
            var $imageFitImage = $imageFit.find('img');
            var $reciept = $('.reciept');
            var $openRules = $('#openrules');
            
            $openRules.click(function(e) {
            	e.preventDefault();
            	$.ajax({
            		url: $(this).attr('href'),
            		success: function(response) {
            			$.modalDialog(response, 'modal-rules');
            			pageTracker._trackPageview($(this).attr('href'));
            		}
            	});
            });
            
			
			$('.input-row.image').mousemove(function(e) {
				$(this).find('input').css({
					left: e.clientX - $(this).offset().left - 30
				});
			});
			
            var error = {
                show: function(response) {
                    $error.hide().text(response.message).fadeIn(1000);
                    $form.find('ul.error_list').remove();
                    for(field in response.fields){
                        $form.find('div.'+field+'"').addClass('js-error');
                        var error =  $form.find('div.'+field+' ul.error_list');
                        
                        if(!error.is('ul')){
                            if(field == 'image'){
                                $image.attr('value','');
                                $image.show().parent().fadeTo(200,1);
                                $imageFit.removeClass('uploaded');
                                $imageFitImage.fadeOut();
                            }else{
                                error = $('<ul class="error_list"><li>'+response.fields[field]+'</li></ul>').hide();
                                error.appendTo($form.find('div.'+field+'"'))
                                .click(function(){
                                    $(this).fadeOut();
                                    $(this).parent().find('input').trigger('focus');
                                    $(this).parent().find('.select-replacement').trigger('click');
                                })
                                .fadeIn(1000);
                            }
                        }else{
                            error.find('li').text(response.fields[field]);
                            error.fadeIn(1000);
                        }
                    }
                },
                hide: function() {
                    $error.fadeOut();
                }
            }
			$image.mousedown($.globals.bubbles.stop);
            $image.change(function() {
                $form.ajaxSubmit({
                    iframe: true,
                    url: '/last-opp/bilde',
                    type: 'post',
                    success: function(data) {
                        data = $.parseJSON(data);
                        $.globals.bubbles.start();
                        if(data.status === 'ok') {
                            error.hide();
							
                            $image.hide().parent().fadeTo(200,0.4);
                            $imageFit.addClass('uploaded');
							
                            $imageFitImage.hide().attr('src', '/uploads'+data.data.url).load(function() {
								
                                var updateCrop = function() {
                                    var position = {
                                        x1: imageFitWrapperOffset.left - $imageFitImage.offset().left,
                                        y1: imageFitWrapperOffset.top - $imageFitImage.offset().top
                                    };
									
                                    position.x2 = position.x1 + $imageFitWrapper.width();
                                    position.y2 = position.y1 + $imageFitWrapper.height();
									
                                    $imageCrop.val('{"x1": '+position.x1+', "y1": '+position.y1+', "x2": '+position.x2+', "y2": '+position.y2+'}');
                                }
								
                                $imageFitImage.draggable({
                                    containment: [
                                    imageFitWrapperOffset.left - ($imageFitImage.width() - $imageFitWrapper.width()),
                                    imageFitWrapperOffset.top - ($imageFitImage.height() - $imageFitWrapper.height()),
                                    imageFitWrapperOffset.left,
                                    imageFitWrapperOffset.top
                                    ],
                                    stop: updateCrop
                                });
								
                                $imageFitImage.css({
                                    left: Math.floor(($imageFitWrapper.width() - $imageFitImage.width()) / 2),
                                    top: Math.floor(($imageFitWrapper.height() - $imageFitImage.height()) / 2)
                                }).fadeIn();
								
                                updateCrop();
                            });
							
                            $form.find('#imageUrl').val(data.data.url);
                        } else {
                            error.show(data);
                        }
                    },
                    error:function(){
                        error.show({message:'Du oppstod en feil, vennligst prøv igjen.'});
                    }
                });
            });
			
            $form.submit(function(e) {
                e.preventDefault();
                $.ajax({
                    url: $form.attr('action'),
                    type: 'post',
                    dataType: 'json',
                    data: $(this).serializeArray(),
                    success: function(response) {
                        if(response.status === 'ok') {
                            $form.hide();
                            $reciept.show();
                            pageTracker._trackPageview('/last-opp/takk');
                        } else {
                            error.show(response);
                        }
                    },
                    error:function(){
                        error.show({message:'Du oppstod en feil, vennligst prøv igjen.'});
                    }
                });
            });
        });
    }
	
	$.modalDialog = function(html, cssClass) {
		var $modal = $('#modal');
		$modal.attr('class', '').addClass(cssClass);
		var $overlay = $modal.find('.overlay');
		var $content = $modal.find('.content');
		var html = html;
		
		$.globals.bubbles.stop();
		
		var closebtn = $('<a href="" class="close"></a>');

		var close = function(e){
			e.preventDefault();
			$content.html('');
			$.globals.bubbles.start();
			$modal.hide();
		}

		closebtn.click(close);
		$overlay.click(close);
		
		$content.html(html).append(closebtn);
		$modal.show();

		$content.css({
			marginLeft: ($content.width() / 2) * -1,
			marginTop: ($content.height() / 2) * -1
		});
	}
	
	$.fn.initVideo = function() {
		return $(this).each(function() {
			swfobject.embedSWF("/flash/Player.swf", $(this).attr('id'), "720", "404", "9.0.0", "expressInstall.swf", {src: '/flash/video.flv'}, {wmode: 'transparent'});
		});
	}
	
	$.fn.initFilmEntrance = function() {
		return $(this).each(function() {
			$(this).click(function(e) {
				e.preventDefault();
				var ready = {
					script: false,
					content: false
				};
				
				var run = function() {
					if(ready.content && ready.script) {
						$('#video').initVideo();
					}
				}
				
				$.ajax({
					url: $(this).attr('href'),
					type: 'get',
					success: function(response) {
						$.modalDialog(response);
						ready.content = true;
						run();
						pageTracker._trackPageview($(this).attr('href'));
					}
				});
				
				$.getScript('/js/swfobject.js', function() {
					ready.script = true;
					run();
				});
			});
		});
	}


    $.fn.labelize = function() {
        return $(this).each(function() {
            var $input = $(this);
            var $label = $('label[for='+$input.attr('id')+']');

            $label.css({
                position: 'absolute',
                left: $input.css('paddingLeft'),
                top: $input.css('paddingTop')
            });

            $input
            .blur(function() {
                if($input.val().length === 0) {
                    $label.fadeTo(200, 1);
                }
            })
            .bind('keypress focus',function() {
                setTimeout(function() {
                    $input.parent().find('.error_list').fadeOut(100);
                    if($input.val().length === 0) {
                        $label.fadeTo(200, .5);
                    } else {
                        $label.fadeOut(100);
                    }
                }, 40);
            });

            if($input.val().length > 0) {
                $label.hide();
            }
        });
    }


    $.fn.gallery = function(){
        return $(this).each(function(){
            var $gallery = $(this);
            var pages;
            var occupied = false;
            var speed = 600;
            var easing = 'easeInOutQuad';

            $gallery.find('.entries').each(function(){
                var $entries = $(this);
                var $pageVisible, $pageNext, $pagePrev;

                $pageVisible = $entries.find('.page:first').data('page',1).attr('id','page1');
                var position = $pageVisible.position();
                var width = $pageVisible.width();
                var nextLeft = position.left;
                var bookWidth = width;
                var $book = $entries.find('.book');
                var addPage = function(pageNumber, callback){
                    occupied = true;
                    callback = (callback === undefined)?function(){}:callback;

                    $book.css('width',(bookWidth += width)+'px');
                    nextLeft += width;
                    $pageNext = $('<div />',{
                        'id':'page'+pageNumber,
                        'class':'page'
                    })
                    .data('page',pageNumber);
                    
                    var $prev = $book.find('#page'+(pageNumber-1));
                    if(!$prev.is('.page')){
                        if($book.find('.page:last').data('page') < pageNumber){
                            $prev = $book.find('.page:last');
                        }
                    }
                    
                    $prev.after($pageNext);
                    $pageNext.load('/side/'+(pageNumber),function(){
                        callback();
                        occupied = false;
                    });
                };

                var prependBook = function(pageNumber,callback){
                    occupied = true;
                    callback = (callback === undefined)?function(){}:callback;
                    if(!$book.find('#page'+pageNumber).is('.page') && pageNumber > 0){
                        bookWidth += width;
                        $book.css('width',bookWidth+'px');
                        $pagePrev = $('<div />',{
                            'id':'page'+pageNumber,
                            'class':'page'
                        });
                        $book.find('#page'+(pageNumber+1)).before($pagePrev);
                        $book.css('left',function(){
                            return (parseInt($(this).css('left'))-width)+'px';
                        });
                        $pagePrev.load(
                            '/side/'+pageNumber,
                            function(){
                                $pagePrev.data('page',pageNumber);
                                callback();
                                occupied = false;
                            }
                            );
                    }else{
                        callback();
                        occupied = false;
                    }
                };

                // Preload page 2
                addPage(2);

                var first = function(){
                    if(!occupied){
                        $.globals.bubbles.stop();
                        $book.stop(false,true).animate(
                            {'left':0},
                            speed,
                            easing,
                            $.globals.bubbles.start
                        );
                        $pageVisible = $book.find('.page:first');
                        return 1;
                    }else{
                        return false;
                    }
                };

                var prev = function(){
                    var pageNumber = $pageVisible.data('page')-1;

                    var changePage = function(){
                        $book.stop(false,true).animate(
                            {'left':'+='+width},
                            speed,
                            easing,
                            function(){
                                $.globals.bubbles.start();
                                $pageVisible = $pageVisible.prev();
                                // Prelaster neste venstre bok dersom den ikke finnes
                                if($pageVisible.prev().data('page') != ($pageVisible.data('page')-1)){
                                    prependBook($pageVisible.data('page')-1);
                                }
                            }
                        );
                    };

                    if(!occupied){
                        $.globals.bubbles.stop();
                        if($pageVisible.prev().data('page') != pageNumber){
                            prependBook(pageNumber,function(){
                                changePage();
                            });
                        }else{
                            changePage();
                        }
                        return pageNumber;
                    }else{
                        return false;
                    }
                }

                var next = function(){
                    var next =  $pageVisible.next().next();
                    var pageNumber = $pageVisible.data('page')+1;

                    if(!occupied){
                        $.globals.bubbles.stop();
                        $book.stop(false,true).animate(
                            {'left':('-='+width)},
                            speed,
                            easing,
                            function(){
                                // Preload next page
                                if(next.data('page') != (pageNumber+1)){
                                    addPage(pageNumber+1,$.globals.bubbles.start);
                                }else{
                                    $.globals.bubbles.start();
                                }
                            }
                        );
                        $pageVisible = $pageVisible.next();
                        return pageNumber;
                    }else{
                        return false;
                    }
                };

                var last = function(lastPage){
                    var goToLastPage = function(){
                        $.globals.bubbles.stop();
                        $pageVisible = $book.find('.page:last');
                        $book.stop(false,true).animate(
                            {'left':'-'+($book.width()-width)+'px'},
                            speed,
                            easing,
                            function(){
                                // Preload pev page
                                if(($pageVisible.prev().data('page') - 1) != lastPage-1){
                                    prependBook(lastPage-1,$.globals.bubbles.start);
                                }else{
                                    $.globals.bubbles.start();
                                }
                            }
                        );
                    }

                    if(!occupied){
                        if($book.find('.page:last').data('page') != lastPage){
                            addPage(lastPage,goToLastPage);
                        }else{
                            goToLastPage();
                        }
                        return lastPage;
                    }else{
                        return false;
                    }
                }

                pages = {
                    page: function(){
                        return $pageVisible.data('page');
                    },
                    first:first,
                    prev:prev,
                    next:next,
                    last:last
                };


                var showEntry = function(href){
                    var $entryBig = $('<div id="big_entry">');
                    $entryBig.load(href,function(){
                        $('#big_entry').fadeOut(200,function(){
                            $(this).remove();
                        });
                        $entryBig
                        .hide()
                        .appendTo('.gallery');

                        location.hash = href;

                        $entryBig.fadeIn('fast');
                        pageTracker._trackPageview(href);
                    });
                };

                var href = location.hash.substr(1);
                if(href.length > 0){
                    showEntry(href);
                }

                $('.gallery .entries .entry').live('click',function(e){
                    e.preventDefault();
                    var href = $(this).attr('href');
                    showEntry(href);
                });

                $('.gallery .entry a.close').live('click',function(e){
                    e.preventDefault();
                    var $entryBig = $(this).closest('.entry');
                    $entryBig.fadeOut('fast',function(){
                        $(this).remove();
                        location.hash = '';
                    });
                });
                
                $('.gallery .entry .share a').live('click',function(e){
                	e.preventDefault();
                	window.open($(this).attr('href'));
                });

                $('.gallery .entry .vote a').live('click',function(e){
                    e.preventDefault();
                    var $entry = $(this).closest('.entry');
                    var href = $(this).attr('href');
                    $.get(href,function(response){
                        if(response == 1){
                            var votes = parseInt($entry.find('.info .votes').text());
                            $entry.find('.info .votes').text((++votes));
                        }
                        $entry.find('.toolbar .vote').fadeOut(150,function() {
                        	$entry.find('.toolbar .voted').fadeIn(150);
                        });
                    });
                });
            });

            $gallery.find('ul.nav').each(function(){
                var $nav = $(this);
                var $first = $nav.find('.first');
                var $last =  $nav.find('.last');
                var $next =  $nav.find('.next');
                var $prev =  $nav.find('.prev');
                var $labelFrom = $nav.find('.label .from');
                var $labelTo = $nav.find('.label .to');
                var $total = $nav.find('.label .total');
                var ceilEntries = parseInt($total.text());
                var entriesPerPage =  $gallery.find('.page:first .entry').length;
                var lastPage = Math.ceil(ceilEntries/entriesPerPage);

                var setLabel = function(page){
                    var from = ((page-1)*entriesPerPage)+1;
                    var to = from+entriesPerPage-1;

                    if(to > ceilEntries){
                        to = ceilEntries;
                    }

                    $labelFrom.text(from);
                    $labelTo.text(to);
                };


                var first = function(e){
                    e.preventDefault();
                    if(pages.page() > 1){
                        var page = pages.first();
                        if(page){
                            setLabel(page);
                            activateNext();
                            activateLast();
                        }
                    }
                    if(page){
                        inactivatePrev();
                        inactivateFirst();
                    }
                }

                var prev = function(e){
                    e.preventDefault();
                    var page = pages.page();
                    if(page > 1){
                        page = pages.prev();
                        if(page){
                            setLabel(page);
                            activateNext();
                            activateLast();
                        }
                    }
                    if(page == 1){
                        inactivatePrev();
                        inactivateFirst();
                    }
                }

                var next = function(e){
                    e.preventDefault();
                    var page = pages.page();
                    if(page < lastPage){
                        page = pages.next();
                        if(page){
                            setLabel(page);
                            activatePrev();
                            activateFirst();
                        }
                    }
                    if(page == lastPage){
                        inactivateNext();
                        inactivateLast();
                    }
                }

                var last = function(e){
                    e.preventDefault();
                    var lastPage = $(this).attr('rel');
                    var page = pages.last(lastPage);
                    if(page){
                        setLabel(page);
                        activatePrev();
                        activateFirst();
                        inactivateNext();
                        inactivateLast();
                    }
                };

                var activateFirst = function(){
                    if(!$first.find('a').is('a')){
                        $first.html('<a />');
                        $first.find('a').click(first);
                    }
                    $first.find('a').removeClass('disabled');
                };

                var inactivateFirst = function(){
                    $first.find('a').addClass('disabled');
                }

                var activatePrev = function(){
                    if(!$prev.find('a').is('a')){
                        $prev.html('<a />');
                        $prev.find('a').click(prev);
                    }
                    $prev.find('a').removeClass('disabled');
                };

                var inactivatePrev = function(){
                    $prev.find('a').addClass('disabled');
                };

                var activateNext = function(){
                    $next.find('a').removeClass('disabled');
                };

                var inactivateNext = function(){
                    $next.find('a').addClass('disabled');
                };

                var activateLast = function(){
                    $last.find('a').removeClass('disabled');
                };

                var inactivateLast = function(){
                    $last.find('a').addClass('disabled');
                };

                $next.find('a').click(next);
                $last.find('a').click(last);

            });

        });


    }

    $.fn.loader = function(options){
        var settings = {
            speed: 200
        };

        $.extend(true,settings,options);

        return $(this).each(function(){
            var $loader, $visible, $next, i;

            var animate = function(){
                $next = $visible.next();
                if($next.length == 0){
                    $next = $loader.find('div.pos-1');
                }

                $visible.stop(true,true).fadeOut(settings.speed);
                $next.stop(true,true).fadeIn(settings.speed, function(){
                    $visible = $next;
                });
            }

            var start = function(){
                i = setInterval(animate,settings.speed+100);
                $loader.show();
            }

            var stop = function(){
                clearInterval(i);
                $loader.hide();
            }

            $loader = $(this).hide();
            $loader.html('<div class="pos-1">&nbsp;</div><div class="pos-2">&nbsp;</div><div class="pos-3">&nbsp;</div>').appendTo('body');
            $loader.find('div:not(.pos-1)').hide();
            $visible = $loader.find('.pos-1');

            $loader.ajaxStart(start);
            $loader.ajaxStop(stop);
        });

    }

    $(function() {
        $.initGlobalsHandler();
        if(!($.browser.msie && $.browser.version.substr(0,1)<7)){
            $('body').addClass('js');
            $('.bubble').initForceSystem();
            $('.gallery').gallery();
            $('<div id="loader">&nbsp;</div>').loader();

            $('#commercial #video').initVideo();
            $('.film-entrance a').initFilmEntrance();

            $('.upload-form').initUploadForm();
            $('.upload-form input, select').focus(function(){
                $.globals.bubbles.stop();
            });
            $('.upload-form input, select').blur(function(){
                $.globals.bubbles.start();
            });

            $('.checkbox').checkboxReplacement();
            $('select:not(.search)').selectBoxReplacement();
            $('select.search').selectSearch();
            $('.upload-form .text, .search .text').labelize();
            
            $('.diploma-print').click(function(e) {
            	e.preventDefault();
            	window.print();
            });
        }
    });

})(jQuery);
