var jsCore = jsCore || {};

jsCore.Base = new Class({

    Implements: Options,

    helperInstance: null,

    /**
     * Constructor
     */
    initialize: function (options, iOptions) {
        (iOptions !== false && typeOf(options) == 'object') && this.setOptions(options);
    },

    /**
     * Class loader
     */
    load: function () {
        jsCore.Class = [];

        Array.from(arguments).each(function (argument) {
            if (typeOf(window[argument[0]]) == 'class') {
                // Callback to class executer
                var extension = function () {
                    jsCore.Class[argument[0]] = new window[argument[0]](argument[1] || {});
                };
                // If need call class after domready event
                if (argument[1] && argument[1].domready === true) {
                    window.addEvent('domready', extension);
                } else {
                    // Call at once
                    extension.call();
                }
            } else {
                throw new Error('Class: ' + argument[0] + ' not exist');
            }
        });
        
        return this;
    },

    /**
     * Return internal parameter on father class
     */
    iGet: function () {
        var section = arguments[0].match(/^(.*?)::(.*)$/);

        if (!section) {
            throw new Error('Incorrect call base getter method');
        }
        
        switch (section[1]) {
            case 'text':
                return typeOf(arguments[1]) == 'object' ? this.options.texts[section[2]].substitute(arguments[2]) : this.options.texts[section[2]];
                break;
            case 'class':
                return this.options.classes[section[2]];
                break;
            case 'object':
                return this.options.objects[section[2]];
                break;
            case 'lang':
                return this.parceOption(key, arguments[2] || globalDynamicLang || {});
                break;
            case 'option':
                return this.parceOption(key, arguments[2] || coreOptions || {});
                break;
            case 'helper':
                if (typeOf(jsCore.helperInstance[section[2]]) != 'function') {
                    throw new Error('Helper: ' + section[2] + ' not exist');
                }
                return jsCore.helperInstance[section[2]].apply(jsCore.helperInstance, Array.from(arguments).slice(1).flatten());
                break;
        }
    },

    /**
     * Parce multiple config value
     */
    parceOption: function (key, store) {
        var propertyName,
        keyArray = key.split("::");
        for (var segment in keyArray) {
            if (keyArray.hasOwnProperty(segment)) {
                propertyName = propertyName == null ? store[keyArray[segment]] : propertyName[keyArray[segment]];
                if (propertyName === undefined) {
                    throw new Error('Error getting section name: ' + keyArray[segment]);
                }
            }
        }
        return propertyName;
    }
    
});

jsCore.Initialize = new Class({
    Extends: jsCore.Base,

    initialize: function (config) {
        jsCore.Config = config;
        jsCore.helperInstance = new jsCore.Helpers();
        return jsCore;
    }
});

jsCore.Helpers = new Class({

    Extends: jsCore.Base,

    elements: {},

    initialize: function () {
        return this;
    },

    go: function (param) {
        window.location.href = param;
    },

    isValidMail: function (str) {
        return str.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/gi);
    },

    isValidUrl: function (str) {
        return str.test(/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/)
    },
    
    imageResize: function (image, width, height, exact) {
                
        var imageSize = image.getSize();

        if ((height / imageSize.y) > (width / imageSize.x)) {
            var widthResize = Math.ceil(imageSize.x * (height / imageSize.y)); 
            return {
                'width': exact ? widthResize: width,
                'height': height,
                'top': 0,
                'left': (widthResize - width) * -0.5
            }
        } else {
            var heightResize = Math.ceil(imageSize.y * (width / imageSize.x)); 
            return {
                'width': width,
                'height': exact ? height : heightResize,
                'top': (heightResize - height) * -0.5,
                'left': 0
            }
        }
    }
});

var Custom = {
    checkboxHeight: 25,
    radioHeight: 17,
    selectWidth: 340,
    init: function() {
        var inputs = document.getElementsByTagName("input"), span = Array(), textnode, option, active;
        for(var a = 0; a < inputs.length; a++) {
            if((inputs[a].type == "checkbox")) {
                span[a] = document.createElement("span");
                span[a].className = inputs[a].type;

                // TODO: chech this in Chrome and IE
                try {
                    span[a].cloneEvents(inputs[a]);
                } catch (e) {}

                if(inputs[a].checked == true) {
                    if(inputs[a].type == "checkbox") {
                        position = "0 -" + (Custom.checkboxHeight*2) + "px";
                        span[a].style.backgroundPosition = position;
                    } else {
                        position = "0 -" + (Custom.radioHeight*2) + "px";
                        span[a].style.backgroundPosition = position;
                    }
                }
                inputs[a].parentNode.insertBefore(span[a], inputs[a]);
                inputs[a].onchange = Custom.clear;
                if(!inputs[a].getAttribute("disabled")) {
                    span[a].onmousedown = Custom.pushed;
                    span[a].onmouseup = Custom.check;
                } else {
                    span[a].className = span[a].className += " disabled";
                }
            }
        }
        inputs = document.getElementsByTagName("select");
        for(a = 0; a < inputs.length; a++) {
            if(inputs[a].className.test("wpcf7-select")) {
                option = inputs[a].getElementsByTagName("option");
                active = option[0].childNodes[0].nodeValue;
                textnode = document.createTextNode(active);
                for(b = 0; b < option.length; b++) {
                    if(option[b].selected == true) {
                        textnode = document.createTextNode(option[b].childNodes[0].nodeValue);
                    }
                }
                span[a] = document.createElement("span");
                span[a].className = "select";
                span[a].id = "select" + inputs[a].name;
                span[a].appendChild(textnode);
                inputs[a].parentNode.insertBefore(span[a], inputs[a]);
                if(!inputs[a].getAttribute("disabled")) {
                    inputs[a].onchange = Custom.choose;
                } else {
                    inputs[a].previousSibling.className = inputs[a].previousSibling.className += " disabled";
                }
            }
        }
        document.onmouseup = Custom.clear;
    },
    pushed: function() {
        element = this.nextSibling;
        if(element.checked == true && element.type == "checkbox") {
            this.style.backgroundPosition = "0 -" + Custom.checkboxHeight*3 + "px";
        } else if(element.checked == true && element.type == "radio") {
            this.style.backgroundPosition = "0 -" + Custom.radioHeight*3 + "px";
        } else if(element.checked != true && element.type == "checkbox") {
            this.style.backgroundPosition = "0 -" + Custom.checkboxHeight + "px";
        } else {
            this.style.backgroundPosition = "0 -" + Custom.radioHeight + "px";
        }
    },
    check: function() {
        element = this.nextSibling;
        if(element.checked == true && element.type == "checkbox") {
            this.style.backgroundPosition = "0 0";
            element.checked = false;
        } else {
            if(element.type == "checkbox") {
                this.style.backgroundPosition = "0 -" + Custom.checkboxHeight*2 + "px";
            } else {
                this.style.backgroundPosition = "0 -" + Custom.radioHeight*2 + "px";
                group = this.nextSibling.name;
                inputs = document.getElementsByTagName("input");
                for(var a = 0; a < inputs.length; a++) {
                    if(inputs[a].name == group && inputs[a] != Custom.nextSibling) {
                        inputs[a].previousSibling.style.backgroundPosition = "0 0";
                    }
                }
            }
            element.checked = true;
        }
    },
    clear: function() {
        inputs = document.getElementsByTagName("input");
        for(var b = 0; b < inputs.length; b++) {
            if(inputs[b].type == "checkbox" && inputs[b].checked == true && inputs[b].className.test("customize")) {
                inputs[b].previousSibling.style.backgroundPosition = "0 -" + Custom.checkboxHeight*2 + "px";
            } else if(inputs[b].type == "checkbox" && inputs[b].className.test("customize")) {
                inputs[b].previousSibling.style.backgroundPosition = "0 0";
            } else if(inputs[b].type == "radio" && inputs[b].checked == true && inputs[b].className.test("customize")) {
                inputs[b].previousSibling.style.backgroundPosition = "0 -" + Custom.radioHeight*2 + "px";
            } else if(inputs[b].type == "radio" && inputs[b].className.test("customize")) {
                inputs[b].previousSibling.style.backgroundPosition = "0 0";
            }
        }
    },
    choose: function() {
        option = this.getElementsByTagName("option");
        for(var d = 0; d < option.length; d++) {
            if(option[d].selected == true) {
                document.getElementById("select" + this.name).childNodes[0].nodeValue = option[d].childNodes[0].nodeValue;
            }
        }
    }
}

window.addEvent('domready', Custom.init);


var formParser = new Class({
    Implements: Options,

    formHash: new Hash(),
    keyCache: new Hash(),
    
    options: {
        ignoreEmpty: false,
        filterName: [],
        filterElement: []
    },
    initialize: function(el,options) {
        this.setOptions(options);
        this.form = document.id(el);
        this.formHash.empty();
        return this.parse();
    },
    getPair: function (key) {
        var splName = key.match(/(\S+)\[(|\w+)\]/);
        return !!(splName || splName === 0) ? {
            'v': splName[1],
            'p': true,
            's': splName[2]
        } : {
            'v': key,
            'p': false,
            's': null
        }
    },
    getPairName: function (key) {
        if (!!(this.getPair(key).s || this.getPair(key).s === 0)) {
            return this.getPair(key).s;
        }
        else {
            var name = this.keyCache.get(this.getPair(key).v)+1;
            this.keyCache.set(this.getPair(key).v,name);
            return name;
        }
    },
    setPair: function (k,v) {
        if (!!!(k || k === 0) || (this.options.ignoreEmpty && !!!(v || v === 0))) return;
        if (this.options.filterName.length > 0 && this.options.filterName.indexOf(this.getPair(k).v) == -1) return;
        if (!this.keyCache.has(this.getPair(k).v)) this.keyCache.set(this.getPair(k).v,-1);
        if (this.getPair(k).p && this.formHash.has(this.getPair(k).v) && typeOf(this.formHash.get(this.getPair(k).v)) == 'array')
            this.formHash.get(this.getPair(k).v).push({
                'key': this.getPairName(k),
                'value': v
            });
        else if (this.getPair(k).p)
            this.formHash.set(this.getPair(k).v,[{
                    'key': this.getPairName(k),
                    'value': v
                }]);
            else
                this.formHash.set(this.getPair(k).v,v);
        },
        parse: function () {
            var allElements = this.form.getElements("input,select,textarea");
            allElements.each(function (e) {
                if (this.options.filterElement.length > 0 && this.options.filterElement.indexOf(e.type) == -1) return;
                switch (e.type) {
                    case 'text':
                    case 'password':
                    case 'hidden':
                    case 'textarea':
                    case 'submit':
                        this.setPair(e.get('name'),e.get('value'));
                        break;
                    case 'radio':
                    case 'checkbox':
                        if (e.get('value') != false && e.get('checked') != false) this.setPair(e.get('name'),e.get('value'));
                        break;
                    case 'select-one':
                        this.setPair(e.get('name'),e.get('value'));
                        break;
                    case 'select-multiple':
                        e.get('value').each(function (xpc) {
                            this.setPair(e.get('name'), xpc);
                        },this);
                        break;
                }
            },this);
            return this.formHash;
        }
    });

    var slideShow = new Class({
    
        Extends: jsCore.Base,

        elements: {
            controllElement: [],
            imageElement: []
        },
        active: 0,
        autoslide: 0,
        timer: null,
        loaderTimer: null,
        idle: false,
        evened: false,

        options: {
            'autochange': {
                'enable': true,
                'interval': 3000
            },
            'colors': {
                'activeSquare': '#A8A8A8',
                'unactiveSquare': '#FFF'
            },
            'imageobserver': {
                'enable': true,
                'interval': 100
            },
            'classes': {
                'active': 'active'
            }

        },

        initialize: function(options) {
            this.parent(options);
            this.grabObjects(this.elements, this.options.objects);
            this.images = this.options.images;
        },

        start: function () {
            if (this.images.length == 0) return false;
            this.attachControlls();
            this.attachImages();
            this.autoChange();
        },
    
        stop: function () {
            clearInterval(this.timer);  
        },

        autoChange: function () {
            if (this.options.autochange.enable === false) return false;
   
            this.timer = setInterval(function() {
                this.autoslide = (this.autoslide < this.images.length - 1) ? this.autoslide + 1 : 0;
                this.changeSlide(this.autoslide, false);
            }.bind(this), this.options.autochange.interval);
        },

        attachImages: function () {
            this.images[0] = this.elements.imageElement[0] = this.elements.container.getElement('img');
            Array.each(this.images, function (data, index) {
                if (index > 0) {
                    this.elements.imageElement[index] = new Element('img', {
                        'src': data,
                        'styles': {
                            'opacity': 0
                        }
                    }).inject(this.elements.container);
                }
                this.elements.imageElement[index].store('fx', new Fx.Tween(this.elements.imageElement[index], {
                    link: 'cancel'
                }));
                if (this.options.imageobserver.enable === true) {
                    this.elements.imageElement[index].addEvent('load', function () {
                        this.elements.imageElement[index].store('loaded', true);
                    }.bind(this));
                }
            }, this);
        },

        imageObserver: function (slide, callback) {
            if (this.elements.imageElement[slide].retrieve('loaded') == null) {
                this.elements.loader.fade(1);
                this.elements.controllButtons.fade(0);

                this.loaderTimer = setInterval(function () {
                    if (this.elements.imageElement[slide].retrieve('loaded') == true) {
                        clearInterval(this.loaderTimer);
                        this.elements.loader.fade(0);
                        this.elements.controllButtons.fade(1);
                        this.idle = false;
                        callback.attempt(this);
                    }
                }.bind(this), this.options.imageobserver.interval);
                return false;
            } 
        },

        changeSlide: function (slide, manually) {
       
            if (this.active == slide || this.idle) return false;
        
            this.idle = true;

            if (this.options.imageobserver.enable === true && this.imageObserver(slide, this.changeSlide.bind(this, slide, manually)) === false) return false;

            this.stop();
        
            if (manually) {
                this.markActiveControll(slide);
            }

            if (Browser.Features.cssTransitions) {
                this.animationAdvanced(slide, manually);
            } else {
                this.animationSimple(slide, manually);
            }
        
            this.active = slide;
        },
    
        animationSimple: function (slide, manually) {
            this.elements.imageElement[slide].retrieve('fx').start('opacity', 1).chain(function () {
                this.idle = false;
                if (manually) {
                    this.autoslide = slide;
                } else {
                    this.markActiveControll(slide);
                }
                this.autoChange();
            }.bind(this));
            this.elements.imageElement[this.active].retrieve('fx').start('opacity', 0);
        },
    
        animationAdvanced: function (slide, manually) {
            var delayBetweenBars = 70,
            blockSize = 80,
            maxDelayValue = 0,
            maxDelayElement = null;
               
            this.evened = false;
        
            for(var i = 0; i < Math.floor(this.elements.container.getSize().x / blockSize) + 1; i++) {
                for(var j = 0; j < Math.floor(this.elements.container.getSize().y / blockSize) + 1; j++) {
                
                    var delay = Math.floor(Math.random() * delayBetweenBars * 10);
                
                    var element = new Element('DIV', {
                        'class': 'block block-' + i + '-' + j,
                        'styles': {
                            'width': blockSize + 'px',
                            'height': blockSize + 'px',
                            'position': 'absolute',
                            'top': (j * blockSize) + 'px',
                            'left': (i * blockSize) + 'px',
                            'z-index': '1000',

                            'background-image': 'url(' + this.elements.imageElement[this.active].src + ')',
                            'background-position': '-' + (i * blockSize) + 'px -' + (j * blockSize) + 'px'
                        }
                    }).store('delay', delay).inject(this.elements.container);
                
                    this.elements.imageElement[this.active].retrieve('fx').set('opacity', 0);
                
                    if(delay > maxDelayValue) {         
                        maxDelayElement = element;               
                        maxDelayValue = delay;
                    }

                }
            }
        
            this.elements.imageElement[slide].retrieve('fx').set('opacity', 1);
        
            if (typeOf(maxDelayElement) == 'element') {
                maxDelayElement.addEvent('transitionend', function () {
                    if (this.evened === false) {
                        this.elements.container.getElements('div.block').dispose();
                        if (manually) {
                            this.autoslide = slide;
                        } else {
                            this.markActiveControll(slide);   
                        }
                        this.autoChange();
                        this.idle = false;  
                        this.evened = true;
                    }
                }.bind(this));  
            }
        
            clearTimeout(this.timerFx);
            this.timerFx = (function () {
                this.elements.container.getElements('div.block').each(function (element) {
                    new Fx.Tween.CSS3(element, {
                        'property': 'all',
                        'duration': 350,
                        'delay': element.retrieve('delay')
                    }).start('opacity', 0).transform('scale', 0.8); 
                });
            }).delay(50, this);
        },

        markActiveControll: function (slide) {
        
            this.elements.controllElement.each(function (element) {
                element.removeClass(this.iGet('class::active'));
            }, this);
            this.elements.controllElement[slide].addClass(this.iGet('class::active'));
        },

        attachControlls: function () {
            this.elements.controllButtons = new Element('UL');
            var counter = 0;
            Array.each(this.images, function (data, index) {
                ++counter;
                this.elements.controllElement[index] = new Element('LI', {
                    'class': index == 0 ? this.iGet('class::active') : '',
                    'events': {
                        'click': this.changeSlide.bind(this, index, true)
                    }
                }).inject(this.elements.controllButtons);
            }, this);
            this.elements.controllButtons.inject(this.elements.controll);
        }
    });


    var menuSnake = new Class({
        Extends: jsCore.Base,

        elements: {},
        itemsDimension: {},
        snakeLocked: false,
        active: null,

        options: {
            'classes': {
                'snake': 'knob',
                'holder': 'js-holder'
            },
            'backing': 0
        },

        initialize: function (options) {
            this.parent(options);
            this.grabObjects(this.elements, this.options.objects);

            this.buildHTMLStucture();

       
            this.fxSlide = new Fx.Morph(this.elements.knob, {
                'link': 'cancel',
                'transition': Fx.Transitions.Pow.easeOut,
                'duration': 550
            });

            // Get active item
            this.active = this.getActiveItem();

            // Slide to active item if we leave menu panel
            this.elements.container.addEvent('mouseleave', this.slide.bind(this, this.active, false));

            // Attach event's to make slide effect
            this.attachEvents();

            // Force slide to active item
            this.slide(this.active, true);
        },


        buildHTMLStucture: function () {
            this.elements.knob = new Element('DIV', {
                'class': this.iGet('class::snake')
            });
            this.elements.knob.inject(this.elements.snake);
        },

        attachEvents: function () {
            var collection = this.elements.container.getElements('ul.menu>li');
            collection.each(function (item, key) {
            
                // IE7 special fix
                if (Browser.ie7 && typeOf(item.getElement('a')) == 'element') {
                
                    var position = item.getElement('a').getCoordinates(this.elements.container);
                    switch (key) {
                        case 0:
                            this.itemsDimension[item.get('id')] = {
                                'left': position.left - 5,
                                'width': position.width + 5
                            }
                            break;
                        case (collection.length - 2):
                            this.itemsDimension[item.get('id')] = {
                                'left': position.left,
                                'width': position.width + 4
                            }
                            break;
                        default:
                            this.itemsDimension[item.get('id')] = {
                                'left': position.left,
                                'width': position.width
                            }      
                    }
                } else {
                    // Create dimension cache
                    this.itemsDimension[item.get('id')] = item.getCoordinates(this.elements.container);
                }
            
                item.addEvents({
                    'mouseenter': this.slide.bind(this, item.get('id'), false),
                    'click': function () {
                        this.snakeLocked = true;
                    }.bind(this)
                });
            }, this);
        },

        getActiveItem: function () {
            return (this.elements.container.getElement('ul>li.current_page_item') ? this.elements.container.getElement('ul>li.current_page_item') : this.elements.container.getElement('ul>li')).get('id');
        },

        slide: function (section, force) {
            if (this.snakeLocked) return false;
            this.fxSlide[force ? 'set' : 'start'].call(this.fxSlide, {
                'left': this.itemsDimension[section].left - this.options.backing.toInt() / 2,
                'width': this.itemsDimension[section].width + this.options.backing
            })  
        }
    });


    var menuElements = new Class({
        Extends: jsCore.Base,

        elements: {
            'subMenus': []
        },
    
        fx: [],
        dimensions: [],
        subMenus: [],
  

        options: {
            'classes': {}
        },

        initialize: function (options) {
            this.parent(options);
            this.grabObjects(this.elements, this.options.objects);
        
            this.attachEvents();
        },

        attachEvents: function () {
            this.elements.container.getElements('div.sub-menu').each(function (item) {
                var ID = item.getElement('ul').get('rel');
            
                this.elements.subMenus[ID] = item;
                this.dimensions[ID] = item.getSize().y;
            
            }, this);
        
            // Basic set layers position
            this.reposition();
       
            this.elements.container.getElements('ul.menu>li').each(function (item) {
                var ID = item.get('rel');
                if (item.hasClass('has-sub-item') && typeOf(this.elements.container.getElement('ul[rel=' + ID + ']')) == 'element') {
                
                    this.fx[ID] = new Fx.Tween(this.elements.subMenus[ID], {
                        'link': 'cancel', 
                        'transition': 'quart:out'
                    }); 
                    
                    item.addEvents({
                        'mouseenter': this.show.bind(this, ID),
                        'mouseleave': this.hide.bind(this, ID)
                    }); 
                
                    this.elements.subMenus[item.get('rel')].cloneEvents(item);
                }
            }, this);
        
            window.addEvent('resize', this.reposition.bind(this));
        },
    
    
        reposition: function () {
            var offset = 22;
            switch (Browser.name) {
                case 'firefox':
                    offset = Browser.Platform.win ? offset : 23;
                    break;
                case 'chrome':
                    offset = 37;
                    break;            
            }
       
            this.elements.container.getElements('div.sub-menu').each(function (item) {
                var ID = item.getElement('ul').get('rel');
            
                if (typeOf(document.id('menu_item_object_' + ID)) == 'element') {
                    var position = document.id('menu_item_object_' + ID).getCoordinates();
                    item.setStyles({
                        'height': 0,
                        'top': position.top + offset,
                        'left': position.left
                    });
                }
            }, this);
        },
    
        itemColor: function (ID, color) { 
            if (typeOf(document.id('menu_item_object_' + ID)) != 'element') return false;
            document.id('menu_item_object_' + ID).getElement('a').setStyle('color', color);  
        },

        show: function (ID) {
            this.fx[ID].start('height', this.dimensions[ID]);
            this.itemColor(ID, '#E39B00');
        },

        hide: function (ID) {
            this.fx[ID].start('height', 0); 
            this.itemColor(ID, '#515151');
        }
    });


    var contactMap = new Class({
        Extends: jsCore.Base,

        elements: {},

        options: {
            objects: {}
        },

        initialize: function(options) {
            this.parent(options);
            this.grabObjects(this.elements, this.options.objects);
            this.create();
            this.marker();

        },
   

        create: function () {
            this.map = new google.maps.Map(this.elements.container, {
                zoom: this.options.zoom,
                streetViewControl: false,
                mapTypeControl: false,
                center: new google.maps.LatLng(this.options.map[0], this.options.map[1]),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });
        },

        marker: function () {
            this.marker = new google.maps.Marker({
                position: new google.maps.LatLng(this.options.marker[0], this.options.marker[1]),
                animation: google.maps.Animation.DROP,
                map: this.map,
                title: this.options.text
            });
        
            google.maps.event.addListener(this.marker, 'click', function () {
                this.marker.setAnimation(this.marker.getAnimation() != null ? null : google.maps.Animation.BOUNCE);
            }.bind(this));

        }
    });



    var contactForm = new Class({
        Extends: jsCore.Base,

        elements: {},
        formChecker: [],
        idle: false,

        options: {
            'objects': {},
            'classes': {
                'message': 'form-message',
                'loading': 'form-message-loading',
                'error': 'form-message-error',
                'sucess': 'form-message-sucess'
            },
            'texts': {
                'loading': 'Sending. Please wait',
                'sucess': 'Message sent successfully',
                'fail': 'Internal sending error. Try again later'
            }
        },

        initialize: function(options) {
            this.parent(options);
            this.grabObjects(this.elements, this.options.objects);
            this.elements.form = this.elements.container.getElement('form');
            this.formChecker = new FormCheck(this.elements.form);
            this.buildHTML();
            this.attachEvents();
        },

        buildHTML: function () {
            this.elements.message = this.elements.container.getElement('span.respons');
        },

        attachEvents: function () {
            this.elements.form.addEvent('submit', function (e) {
                e.stop();
                this.process();
            }.bind(this));
        },

        process: function () {
            if (this.formChecker.isFormValid() === false || this.idle) return false;
            this.idle = true;
            var form = new formParser(this.elements.form);

            this.setMessage('show', this.iGet('text::loading'), this.iGet('class::loading'));
            this.request = new Request.JSON({
                url: jsCore.Config.path.base + '/ajax.php?contact',
                onComplete: function (json) {
                    if (!json) return false;
                    this.idle = false;
                    if (json.result == 1) {
                        this.clearForm();
                        this.setMessage('show', this.iGet('text::sucess'), this.iGet('class::sucess'));
                    } else {
                        this.setMessage('show', this.iGet('text::fail'), this.iGet('class::error'));
                    }
                }.bind(this)
            }).POST(form);
        },
    
        clearForm: function () {
            // Clear native elements 
            this.elements.form.getElements('input[type=text]').setProperty('value', '');
            this.elements.form.getElements('select').set('value', '- select one -');
            this.elements.form.getElements('input[type=checkbox]').set('checked', false);
        
            // Clear custom elements
            this.elements.form.getElements('span.checkbox').setStyle('background-position', '0 0');
            this.elements.form.getElements('span.select').set('text', '- select one -');

        
        },

        setMessage: function (action, text, className) {
            var display = {
                'show': 'inline',
                'hide': 'none'
            };
            this.elements.message.setStyle('display', display[action]);

            this.elements.message.set('html', text);
            if (className) {
                this.elements.message.className = className;
            }
        }

    });


    var videoPlayers = new Class({
        Extends: jsCore.Base,

        elements: {
            'block': {}
        },
        idle: false,
        thumbURL: 'http://i.ytimg.com/vi/{key}/0.jpg',

        options: {
            'objects': {},
            'caption': 28,
            'classes': {
                'container': 'utube-video-player'
            },
            'data': {}
        },

        initialize: function(options) {
            this.parent(options);
            this.grabObjects(this.elements, this.options.objects);
            this.buildHTML();
        },
    
        safeKey: function (ID) {
            return ID.replace(new RegExp('[^\\w+]', 'g'), '');  
        },
    
        buildHTML: function () {  
            var helpers = new jsCore.Helpers();
            Object.each(this.options.data, function (value, ID) {
                var block = this.elements.block[this.safeKey(ID)] = new Element('DIV', {
                    'class': this.iGet('class::container'),
                    'id': 'uVideoPlayer_' + this.safeKey(ID),
                    'styles': {
                        'overflow': 'hidden',
                        'position': 'relative'
                    }
                }).inject(this.elements.container);
            
                var image = new Element('IMG', { 
                    'src': this.thumbURL.substitute({
                        'key': ID
                    })
                }).inject(this.elements.block[this.safeKey(ID)]);
            
                new Element('P', {
                    'text': (value.caption.length > this.options.caption) ? value.caption.substr(0, this.options.caption) + ' ...' : value.caption
                }).inject(block);
           
                new Element('SPAN', {
                    'events': {
                        'click': this.loadVideo.bind(this, ID)
                    }
                }).inject(block);
           
                image.setStyles(Object.merge({
                    'position': 'absolute'
                }, helpers.imageResize(image, block.getStyle('width').toInt(), block.getStyle('height').toInt(), false)));
            
            }, this)       
        
        },
    
        loadVideo: function (ID) {
            new Swiff("http://www.youtube.com/v/" + ID + "?enablejsapi=1&playerapiid=ytplayer&autohide=1&autoplay=1&showinfo=0", {
                'container': 'uVideoPlayer_' + this.safeKey(ID),
                'width': '215',
                'height': '143'
            });
        }
    });

