/* global $, RX, document, window */ 

// Namespace

var RX = RX || {};

// Modules

(function (region) {
    
    "use strict";
    
    // Dependencies
    
    region.dependencies = {
        
        "jQuery" : "1.6.2",
        "jQuery.hotkeys" : "0.8", 
        "Sammy" : "0.7"
        
    };
    
    // Multiple Choice
    
    region.multiple_choice = function () {
      
        var $form = $('.add-m-multiple-choice'),
            $options = $form.find('li');
        
        $options.click(function () {
            
            var $option = $(this),
                $input = $option.find('input');
            
            if ( $input.is(':checked') ) {
                
                $input.removeAttr('checked');
                
                $option.removeClass('active');
                
            } else {
                
                $input.attr('checked','checked');
                
                $option.addClass('active');
                
            }
            
        });
        
    };
    
    // Single Choice
    
    region.single_choice = function () {
        
        var $form = $('.add-m-single-choice'),
            $options = $form.find('li'),
            $input = $form.find('input:hidden');
        
        $options.click(function () {
            
            var $option = $(this),
                o_id = $option.attr('id');
            
            $option.siblings().removeClass('active').end().addClass('active');
            
            $input.val( o_id );
            
        });
        
    };
    
    // Slideshow API
    
    region.slideshow_api = function (slides) {
        
        this.slides = slides;
        this.current = 0;
        
        var self = this,
            total = self.slides.length,
            current = 0,
            index;
        
        return {
            
            get : function (callback) {
                
                self.slides.eq( current ).stop(true, true).animate({ opacity : 'toggle' }, 500, function () {

                    $(this).hide();

                });

                self.slides.eq( callback() ).stop(true, true).animate({ opacity : 'toggle' }, 500, function () {

                    $(this).show();

                });
                
                current = callback();
                
            },
            get_resize : function (callback) {
                
                self.slides.eq( current ).stop(true, true).animate({ opacity : 'toggle' }, 500, function () {

                    $(this).hide();

                });

                self.slides.eq( callback() )
                    .css({
                    
                        height : function (index, value) {
                        
                        $(this).parent()
                            .stop(true, true)
                            .animate({ height : value }, 250);
                        
                        }
                    
                    })
                    .stop(true, true)
                    .animate({ opacity : 'toggle' }, 500, function () {

                        $(this).show();

                    });
                
                current = callback();
                
            },
            next_slide : function () {
                
                index = current === total - 1 ? 0 : current + 1;
                
                return index;
                
            },
            prev_slide : function () {
                
                var index = current === 0 ? total - 1 : current - 1;
                
                return index;
                
            }
            
        };
        
        
    };
    
    // Store Slideshow
    
    region.store_slideshow = function () {
        
        var $slides = $('.store-slideshow ul li'),
            $controls = $('.store-slideshow nav'),
            $next = $controls.find('.store-slideshow-next'),
            $prev = $controls.find('.store-slideshow-prev');
        
        var api = new region.slideshow_api($slides);
        
        $slides
            .eq(0)
            .css({ height : function (index, value) { $(this).parent().css({ height : value }); } })
            .show();
        
        if ( $slides.length <= 1 ) { return; }
        
        $controls.show();
        
        $slides.click(function () { api.get_resize(api.next_slide); });
        $next.click(function () { api.get_resize(api.next_slide); });
        $prev.click(function () { api.get_resize(api.prev_slide); });
        
    };
    
    // Press Slider
    
    region.press_slider = function () {
        
        var $slides = $('.press-m ul li'),
            $controls = $('.press-m nav'),
            $next = $controls.find('.press-m-next'),
            $prev = $controls.find('.press-m-prev');
        
        var api = new region.slideshow_api($slides);
        
        $slides.eq(0).show();
        
        if ( $slides.length <= 1 ) { return; }
        
        $controls.show();
        
        $next.click(function () { api.get(api.next_slide); });
        $prev.click(function () { api.get(api.prev_slide); });
        
    };
    
    // Qutoes
    
    region.quotes = function () {
        
        var $slides = $('.quotes-m ul li'),
            $controls = $('.quotes-m nav'),
            $next = $controls.find('.quotes-m-next'),
            $prev = $controls.find('.quotes-m-prev');
        
        var api = new region.slideshow_api($slides);
        
        $slides.eq(0).show();
        
        if ( $slides.length <= 1 ) { return; }
        
        $controls.show();
        
        $next.click(function () { api.get(api.next_slide); });
        $prev.click(function () { api.get(api.prev_slide); });
        
    };
    
    // Slideshow
    
    region.slideshow = function () {
        
        var $slideshow = $('.slideshow'),
            $slides = $slideshow.find('.ss-slide'),
            $controls = $slideshow.find('.ss-controls'),
            $next = $controls.find('.ss-next'),
            $prev = $controls.find('.ss-prev');
        
        var duration = 500;
        
        var auto = $slideshow.hasClass('auto') ? true : false,
            auto_duration = 3000,
            auto_start;
        
        var total = $slides.length, 
            current = 0,
            next = function () {
                
                var index = current === total - 1 ? 0 : current + 1;
                
                return index;
                
            },
            previous = function () {
                
                var index = current === 0 ? total - 1 : current - 1;
                
                return index;
                
            },
            get_slide = function (callback) {
                
                $slides.eq( current ).stop(true, true).animate({ opacity : 'toggle' }, duration, function () {

                    $(this).hide();

                });

                $slides.eq( callback() ).stop(true, true).animate({ opacity : 'toggle' }, duration, function () {

                    $(this).show();

                });

                current = callback();
                
            };
        
        $slides.eq(0).show();
        
        if ( total <= 1 ) { return; }
        
        $controls.show();
        
        if ( auto === true ) {

            auto_start = setInterval(function () { get_slide(next); }, auto_duration);

            $slideshow.hover(
                function () { clearInterval(auto_start); },
                function () { auto_start = setInterval(function () { get_slide(next); }, auto_duration); } 
            );

        }
        
        $next.click(function () { clearInterval(auto_start); get_slide(next); });
        
        $prev.click(function () { clearInterval(auto_start); get_slide(previous); });
        
        if ( $slideshow.hasClass('page') ) {
            
            $slides.click(function () { clearInterval(auto_start); get_slide(next); });
            
        }
          
    };
    
    // Gallery
    
    region.gallery = {};
    
    // Gallery Templates
    
    region.gallery.tmpl = {
        
        loader : function () {
            
            var html = '';
            
            html += '<span class="gallery-loader">';
                html += '<span class="gallery-progress"></span>';
            html += '</span>';
            
            return html;
            
        },
        overlay : function () {
        
            var html = '';
            
            html += '<div class="gallery-overlay">';
                html += '<div class="gallery-header">';
                    html += '<div class="gallery-imprint sprite">RxArt</div>';
                    html += '<ul class="gallery-share">';
                        html += '<li>';
                            html += '<a href="#" class="gallery-facebook sprite" rel="external">Facebook</a>';
                        html += '</li>';
                        html += '<li>';
                            html += '<a href="#" class="gallery-twitter sprite" rel="external">Twitter</a>';
                        html += '</li>';
                    html += '</ul>';
                    html += '<a class="gallery-close sprite pointer">Close</a>';
                html += '</div>';            
                html += '<div class="gallery-slides"></div>';
                html += '<div class="gallery-nav">';
                    html += '<span class="gallery-title"></span>';
                    html += '<span class="gallery-controls">';
                        html += '<a class="gallery-prev sprite pointer">Previous</a>';
                        html += '<a class="gallery-next sprite pointer">Next</a>';
                    html += '</span>';
                    html += '<span class="gallery-index">';
                        html += '<span class="gallery-current"></span>';
                        html += '<span class="gallery-total">/<span class="gallery-total-value"></span></span>';
                    html += '</span>';
                html += '</div>';
            html += '</div>';
            
            return html;
        
        },
        slide : function (data) {
            
            var html = '';
            
            html += '<div class="gallery-slide" style="width:' + data.width + ';">';
                html += '<img src="' + data.image + '" title="' + data.title + '" alt="' + data.title + '" />';
            html += '</div>';
            
            return html;
            
        }
    
    };
    
    // Gallery Slideshow
    
    region.gallery.slideshow = function (json_url) {
        
        this.json_url = json_url;
        
        var self = this,
            curr = 0,
            len = 0,
            facebook_url,
            twitter_url;
        
        var $body = $('body'),
            $overlay = $('.gallery-overlay'),
            $nav = $('.gallery-nav'),
            $slides = $('.gallery-slides'),
            $slide = null,
            $image = null,
            $title = $('.gallery-title'),
            $current = $('.gallery-current'),
            $total = $('.gallery-total-value'),
            $next = $('.gallery-next'),
            $prev = $('.gallery-prev'),
            $close = $('.gallery-close'),
            $facebook = $('.gallery-facebook'),
            $twitter = $('.gallery-twitter');
        
        var get = {
            
                slide : function (idx) {
                    
                    curr = idx;
                    
                    overlay.loader.init();
                    
                    $.getJSON(self.json_url, function (data) {

                        $slide = $( self.tmpl.slide( data.slides[idx] ) );
                        
                        $image = $slide.find('img');
                        
                        len = data.slides.length;
                        
                        $slides.empty().append( $slide );
                        
                        slide.center( window );
                        
                        $image.load(function () {
                            
                            $('.gallery-loader').remove();
                            
                            $image.fadeTo(250, 1);

                            $title.text( data.slides[idx].title );
                            
                            $current.text( idx + 1 );
                            
                            $total.text( len );
                            
                        });
                        
                        facebook_url = 'http://www.facebook.com/sharer.php?u='+ window.location + '&t=RxArt: ' + data.slides[idx].title;
                        
                        twitter_url = 'http://twitter.com/share?url=' + window.location + '&text=RxArt: ' + data.slides[idx].title;
                        
                        $facebook.attr('href', facebook_url);
                        
                        $twitter.attr('href', twitter_url);
                        
                    });
                    
                },
                next_slide : function () {
                    
                    var next = curr + 1;
                    
                    if ( next === len ) { next = 0; }
                    
                    return next;
                
                },
                prev_slide : function () {
                
                    var prev = curr - 1;
                
                    if ( prev === -1 ) { prev = len - 1; }
                
                    return prev;
                
                }
            
            },
            overlay = {
                
                slide_in : function (idx) {
                    
                    $('body, html').animate({ scrollTop : 0 }, 500);
                    
                    $(document)
                        .bind('keydown', 'right', function () { get.slide( get.next_slide() ); })
                        .bind('keydown', 'left' , function () { get.slide( get.prev_slide() ); })
                        .bind('keydown', 'esc', function () { overlay.slide_out(); })
                        .bind('keydown', 'down', function () { return false; });
                    
                    $overlay.animate({ width : '100%' }, 500, function () {

                        $body.css('overflow','hidden');
                        
                        $nav.animate({ width : '100%' }, 500, function () {
                            
                            get.slide(idx);
                            
                        });
                        
                    });
                    
                },
                slide_out : function () {
                    
                    $body.css('overflow','visible');
                    
                    $(document).unbind('keydown');
                    
                    $overlay.stop(true, true).animate({ width : 0 }, 500, function () { 
                    
                        $slides.empty();
                    
                    });
                    
                    $nav.animate({ width : 0 }, 500);
                    
                },
                loader : {
                    
                    animate : function () {
                        
                        var $progress = $('.gallery-progress');

                        var opts = {
                                step    : 450,
                                frames   : 10,
                                interval : 100
                            },
                            end = -( opts.step * (opts.frames - 1) );

                        setInterval(function () {

                            $progress.css({

                                left : function (index, value) {

                                    var left = parseFloat(value);

                                    left -= opts.step; 

                                    if ( left < end ) { left = 0; }

                                    return left;

                                }

                            });

                        }, opts.interval);
                        
                    },
                    center : function (window) {
                        
                        var $window = $(window),
                            $loader = $('.gallery-loader');

                        var loader_height = $loader.height(),
                            loader_width = $loader.width(),
                            window_height = $window.height(),
                            window_width = $window.width();

                        var position_top = (window_height - loader_height) / 2,
                            position_left = (window_width - loader_width) / 2;

                        $loader.css({

                            top : position_top,
                            left : position_left

                        });
                        
                    },
                    init : function () {
                        
                        $overlay.prepend(self.tmpl.loader);

                        overlay.loader.animate();

                        overlay.loader.center(window);

                        $(window).resize(function () { 

                            overlay.loader.center(this);

                            slide.center(this);

                        });
                        
                    }
                    
                }
                
            },
            slide = {
                
                center : function (window) {
                    
                    var $window = $(window),
                        $slide = $overlay.find('.gallery-slide');

                    var window_height = $(window).height(),
                        slide_height = $slide.height(),
                        padding_top = (window_height - slide_height) / 2;

                    $overlay.css({ paddingTop : padding_top });
                    
                }
                
            },
            bind_controls = function () {
                
                $next.click(function () { get.slide( get.next_slide() ); });
                
                $prev.click(function () { get.slide( get.prev_slide() ); });
                
                $close.click(function () { overlay.slide_out(); });
                
            };
        
        return {
            
            overlay_slide_in : overlay.slide_in,
            
            bind_controls : bind_controls
            
        };
        
    };
    
    // Gallery Init
    
    region.gallery.init = function (json_url, wrapper) {
        
        this.json_url = json_url;
        this.wrapper = wrapper;
        
        var self = this,
            slideshow;
        
        var $body = $('body'),
            $wrapper = $(self.wrapper),
            $nodes = $wrapper.children(),
            $node;
        
        if ( !$nodes ) { return; }
        
        $body.prepend( self.tmpl.overlay() );
        
        slideshow = self.slideshow(json_url);
        
        slideshow.bind_controls();
        
        $nodes.each(function (idx) {

            $node = $(this);

            $node.click(function (e) {

                e.preventDefault();
                
                slideshow.overlay_slide_in(idx);
                
            });

        });
        
    };
    
    // Collapse Header
    
    region.collapseHeader = function (window) {
        
        var $header = $('#header .content'),
            $window = $(window),
            windowWidth = $window.width();
        
        var methods = {
                
                set_width_full: function () {
                    
                    $header
                        .removeClass('width-full')
                        .addClass('width-960');
                    
                },
                set_width_960: function () {
                    
                    $header
                        .removeClass('width-960')
                        .addClass('width-full');
                        
                }
                
            };
        
        return windowWidth < 960 ? methods.set_width_full() : methods.set_width_960();
        
    };
    
    // Checkbox
    
    region.checkbox = function () {
        
        var $trigger = $('.fauxbox');
        
        $trigger.click(function () {
            
            var $this = $(this),
                $checkbox = $this.siblings('input'),
                $sprite = $this.children();
            
            
            if ( $checkbox.is(':checked') ) {

                $checkbox.removeAttr('checked');

            } else {

                $checkbox.attr('checked','true');

            }
            
            $sprite.css({

                backgroundPosition : function (index, value) {

                    return parseFloat(value) === 0 ? '-25px -200px' : '0px -200px';

                }

            });
            
        });
        
    };
    
    // Contact
    
    region.contact = function () {
        
        var on_success = function () {
                
                $('#contact-success').show();
                
            };
        
        // Form Validation
        region.validate('.contact-form', on_success);
        
    };
    
    // Form Placeholder
    
    region.overlabel = function () {
        
        var $forms = $(arguments);
        
       $forms.each(function () {
           
           var  $form = $(this),
                $inputs = $form.find('input.text');
           
           $inputs.each(function () {
                
                var $input = $(this),
                    $label = $input.siblings('label');
                    
                if ( $input.val() == '' ) { $label.show(); } else { $label.hide(); }
                
                $input.focus(function () { $label.hide(); });
                
                $input.blur(function () { if ( $input.val() === '' ) { $label.show(); } });
                
            });
            
       });
        
    };
    
    // Form Validation
    
    region.validate = function (form, callback) {
        
        var $form = $(form),
            $inputs = $form.find('.required');
        
        // Overlabel
        
        $inputs.each(function () {

            var $input = $(this),
                $label = $input.siblings('label'),
                $error = $input.siblings('.error');
            
            if ( $input.val() === '' ) { $label.show(); }
            
            $input.focus(function () { $label.hide(); $error.hide(); });

            $input.blur(function () { if ( $input.val() === '' ) { $label.show(); } });

        });
        
        // Form Handler
        
        $form.submit(function (e) {
            
            var is_valid = false,
                states = [];
            
            // Input Validation
            
            $inputs.each(function (i) {
                
                var $input = $(this),
                    input_value = $input.val(),
                    input_type = $input.attr('class').split(' ').pop();
                    
                var $error = $input.siblings('.error');
                
                var field = {
                        
                        is_empty : function (value) {
                            
                            return value === '' ? true : false;
                            
                        },
                        is_alphabet : function (value) {
                            
                            var regex = /^[a-zA-Z'']+$/;
                            
                            return regex.test( value.split(' ').join('') );
                            
                        },
                        is_phone : function (value) {
                            
                            var regex = /^[0-9]+$/;
                            
                            return regex.test( value.replace(/[^0-9]/g, '') );
                            
                        },
                        is_email : function (value) {
                            
                            var regex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
                            
                            return regex.test(value);
                        }
                        
                    };
                
                $input.val( input_value.trim() );
                
                if ( !field.is_empty( input_value ) ) {
                    
                    switch (input_type) {
                        
                        case 'name' :
                            
                            if ( !field.is_alphabet( input_value ) ) {
                                
                                $error.text('Invalid Name').show();
                                
                                states.push('false');
                                
                            } else {
                                
                                states.push('true');
                                
                            }
                            
                            break;
                        
                        case 'email' :
                        
                            if ( !field.is_email( input_value ) ) {
                                
                                $error.text('Invalid Email').show();
                                
                                states.push('false');

                            } else {
                                
                                states.push('true');
                                
                            }
                            
                            break;
                        
                        case 'phone' :

                            if ( !field.is_phone( input_value ) ) {

                                $error.text('Invalid Phone Number').show();

                                states.push('false');

                            } else {

                                states.push('true');

                            }

                            break;
                    
                        
                        default : 
                        
                            break;
                        
                    }
                    
                } else {
                    
                    $error.text('Field Is Empty').show();
                    
                    states.push('false');
                    
                }
                
            });
            
            Array.prototype.contains = function (obj) {
                
                var i = this.length;
                
                while (i--) {
                    
                    if ( this[i] === obj ) {
                        
                        return true;
                        
                    }
                    
                }
                return false;
            };
            
            if ( !states.contains('false') ) { is_valid = true; }
            
            // Ajax Submit
            
            e.preventDefault();
            
            if (is_valid) {
                
                $.ajax({
                    type    : 'POST',
                    url     : $(this).attr('action'),
                    data    : $(this).serialize(),
                    success : function () {
                        
                        callback();
                        
                    }
                });
               
            }
            
            return states;
            
        });
        
    };
    
    // Tooltip
    
    region.tooltip = {
        
        animate : function () {
            
            var $tooltip = $('.newsletter-tooltip'),
                $show = $('.ntt-show'),
                $hide = $('.ntt-hide');

            var tooltip = {

                    show : function () {

                        $tooltip.stop(true, true).animate({ top : 50 }, 300);
                        $show.addClass('active');
                        
                    },
                    hide : function () {

                        $tooltip.stop(true, true).animate({ top : -255 }, 300, function () {

                            $hide.removeClass('focus');

                        });

                        $show.removeClass('active');

                    }
                };

            $show.click(function () { tooltip.show(); });

            $hide.click(function () { 

                $hide.addClass('focus');

                tooltip.hide(); 

            });
            
        },
        on_success : function () {
            
            var $form = $('.ntt-form'),
                $success = $('.ntt-success');
            
            $form.animate({
                
                opacity : 'toggle'
                
            }, 500, function () {
                
                $success.show();
                
            });
            
        },
        init : function () {
            
            this.animate();
            
            region.validate('.ntt-form', this.on_success);
            
        }
        
    };
    
    // Radio Select
    
    region.radio_select = function () {
        
        var $form = $('.amount-to-give'),
            $radio = $form.find('.amount-other-radio'),
            $input = $form.find('.amount-other');
        
        $form.change(function () {
            
            if ( $radio.is(':checked') ) {
                
                $input.focus();
                
            } else {
                
                $input.val('');
                
                $radio
                    .val('0')
                    .removeAttr('checked');
                
            }
        });
        
        $input
            .change(function () {
                
                $radio.val( $(this).val() );
            
            })
            .focus(function () {
                
                $radio.attr('checked', 'checked');
                
            });
        
    };
    
    // Form Select
    
    region.form_select = function () {
        
        var $select = $('.form-select'),
            $trigger = $select.find('h1'),
            $wrapper = $select.find('.form-select-options'),
            $options = $wrapper.find('li'),
            $items = $options.find('a'),
            $title = $trigger.find('.form-select-title a'),
            $input = $select.find('input:hidden');
        
        var o_height = (function () {
                
                var total = 0;
                
                $options.each(function () {
                    
                    total += $(this).outerHeight();
                    
                });
            
                return total;
                
            }()),
            o_length = $options.length;
        
        $trigger.click(function () {
            
            $wrapper.css({
                
                height : function (index, value) {
                    
                    return parseFloat(value) === 0 ? o_height : 0;
                    
                }
                
            });
            
        });
        
        $items.click(function () {
            
            var option = $(this).text();
            
            $title.text(option);
            
            $input.attr('value', ''+ option +'');
            
            $wrapper.css({ height : 0 });
            
        });
        
    };
    
    region.category_select = function () {
        
        var $dropdown = $('.category-select-m'),
            $trigger = $dropdown.find('h3'),
            $sprite = $trigger.find('.sprite'),
            $menu = $dropdown.find('ul'),
            $items = $menu.find('li');
        
        var total = (function () {

                var height = 0;

                $items.each(function () {

                    height += $(this).outerHeight();

                });

                return height;

            }());
        
        $trigger.click(function () {
            
            $menu.css({
                
                height : function (index, value) {
                    
                    var y = parseFloat(value);
                    
                    if ( y === 0 ) {
                        
                        $sprite.css('backgroundPosition', '-125px -100px');
                        
                    } else {
                        
                        $sprite.css('backgroundPosition', '-100px -100px');
                        
                    }
                    
                    return y === 0 ? total : 0;
                    
                }
                
            });
            
        });
        
    };
    
    // External Links
    region.rel_external = function () {
        
        var $links = $('a:[rel*=external]');
        
        $links.live('click', function () {
            
            window.open(this.href);
            
            return false;
        });
    };
   
    // Add This
    region.add_this = function () {
        
        var $add = $('.add-this');
        
        if ( $add.length ) {
            
            (function() {
                
                var at = document.createElement('script'),
                    s = document.getElementsByTagName('script')[0];
                    
                at.type = 'text/javascript';
                at.async = true;
                at.src = 'http://s7.addthis.com/js/250/addthis_widget.js#pubid=xa-4e4c394d670cc692';
                
                s.parentNode.insertBefore(at,s);
            
            }());
        }
    };
   
    // View Select
   
    region.view_select = function () {
        
        var $view = $('.view-select-m'),
            $trigger = $view.find('h3'),
            $sprite = $trigger.find('.sprite'),
            $menu = $view.find('.view-select-menu'),
            $ul = $menu.find('ul'),
            $li = $ul.find('li'),
            $nav = $menu.find('nav'),
            $down = $nav.find('.view-select-down'),
            $up = $nav.find('.view-select-up');
        
        var li_y = $li.eq(0).outerHeight(),
            li_len = $li.length,
            li_max = 12,
            ul_max_height = li_y * li_len,
            ul_min_height = li_y * li_max,
            menu_height = ul_min_height + 20;
        
        var remaining = 0,
            slide = {
                
                down : function () {
                    
                    $ul.stop(true, true).animate({

                        top : '-=' + ul_min_height

                    }, 500, function () {
                        
                        slide.callback();
                        
                    });
                    
                },
                up : function () {
                    
                    $ul.stop(true, true).animate({

                        top : '+=' + ul_min_height

                    }, 500, function () {
                        
                        slide.callback();
                        
                    });
                    
                },
                callback : function () {
                    
                    remaining = ul_max_height - Math.abs( $ul.position().top );
                    
                    if ( remaining <= ul_min_height ) {
                        
                        $up.show();
                        $down.hide();
                        
                        
                    } else if ( $ul.position().top >= 0 ) {
                        
                        $down.show();
                        $up.hide();
                        
                    }
                    
                }
                
            };
        
        if ( li_len > li_max ) { 
            
            menu_height += 50;
            
            $nav.show();
            
            $down.click(function () {

                remaining = ul_max_height - Math.abs( $ul.position().top );

                if ( !remaining <= ul_min_height ) { slide.down(); }

            });

            $up.click(function () {

                if ( !$ul.position().top >= 0 ) { slide.up(); }

            });
            
        } else {
            
            menu_height = ul_max_height + 20;
            
        }
        
        $trigger.click(function () {
            
            $menu.css({
                
                height : function (index, value) {
                    
                    var y = parseFloat(value);
                    
                    if ( y === 0 ) {
                        
                        $sprite.css('backgroundPosition', '-125px -100px');
                        
                    } else {
                        
                        $sprite.css('backgroundPosition', '-100px -100px');
                        
                    }
                    
                    return y === 0 ? menu_height : 0;
                    
                }
                
            });
            
        });
        
    };
   
       // Map
   
    region.map = {
        
        lat : null,
        lng : null,
        init : function () {
            
            if ( $('.map-m').length ) {
                
                var script = document.createElement("script");
                
                script.type = "text/javascript";
                script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=RX.map.build";
                
                document.body.appendChild(script);
        
            }
        
        },
        build : function () {
            
            var self = this,
                location = new google.maps.LatLng(self.lat, self.lng),
                opts = { zoom: 3, center: location, disableDefaultUI: true, mapTypeId: google.maps.MapTypeId.ROADMAP },
                map = new google.maps.Map(document.getElementById("canvas"), opts),
                image = new google.maps.MarkerImage( '/assets/css/marker.png', new google.maps.Size(44,44), new google.maps.Point(0,0), new google.maps.Point(22,44) ),
                shadow = new google.maps.MarkerImage( '/assets/css/shadow.png', new google.maps.Size(70,44), new google.maps.Point(0,0), new google.maps.Point(22,44) ),
                shape = { coord: [28,0,31,1,33,2,34,3,35,4,37,5,38,6,38,7,39,8,40,9,41,10,41,11,42,12,42,13,42,14,43,15,43,16,43,17,43,18,43,19,43,20,43,21,43,22,43,23,43,24,43,25,43,26,43,27,43,28,42,29,42,30,42,31,41,32,41,33,40,34,39,35,38,36,38,37,37,38,35,39,34,40,33,41,31,42,28,43,15,43,12,42,10,41,9,40,8,39,6,38,5,37,5,36,4,35,3,34,2,33,2,32,1,31,1,30,1,29,0,28,0,27,0,26,0,25,0,24,0,23,0,22,0,21,0,20,0,19,0,18,0,17,0,16,0,15,1,14,1,13,1,12,2,11,2,10,3,9,4,8,5,7,5,6,6,5,8,4,9,3,10,2,12,1,15,0,28,0], type: 'poly' },
                marker = new google.maps.Marker({draggable: false, raiseOnDrag: false, icon: image, shadow: shadow, shape: shape, map: map, position: location });
        
        }
    
    };
    
    region.tweet = function (username) {
        
        var t_url = 'http://search.twitter.com/search.json?callback=?&rpp=1&q=from:' + username,
            t_follow_url = 'https://twitter.com/intent/user?screen_name=' + username,
            t_date = $('#tweet-date'),
            t_text = $('#tweet'),
            t_follow = $('#tweet-follow');
        
        var t_append_script = function () {
                
                var script = document.createElement("script");
                
                script.type = "text/javascript";
                script.src = "http://platform.twitter.com/widgets.js";
                
                document.body.appendChild(script);
                
            },
            t_vertically_center = function () {

                var t_height = t_text.outerHeight(),
                    t_padding = ( 230 - t_height ) / 2; 

                t_text.css({ paddingTop : t_padding });

            };
        
        if ( !t_text.length ) { return; }
        
        t_append_script();
        
        $.getJSON(t_url, function (data) {
            
            var results = data.results[0];
            
            t_date.text( results.created_at.split(' ').slice(1, 3).join(' ') ).show();
            t_text.text( results.text );
            
            t_vertically_center();
            
            t_follow.attr('href', t_follow_url);
            
        });
        
    };
    
    region.gallery_slider = function () {
        
        var $ul = $('.gallery-m ul'),
            $li = $ul.find('li'),
            $b = $('.gallery-m-backward'),
            $f = $('.gallery-m-forward');
    
        var li_y = $li.eq(0).outerWidth(),
            li_len = $li.length,
            li_max = 8,
            ul_max_width = li_y * li_len,
            ul_min_width = li_y * li_max;
        
        var remaining = 0,
            slide = {
                
                b : function () {
                    
                    $ul.stop(true, true).animate({

                        left : '+=' + ul_min_width

                    }, 500, function () {
                        
                        slide.r();
                        
                    });
                    
                },
                f : function () {
                    
                    $ul.stop(true, true).animate({

                        left : '-=' + ul_min_width

                    }, 500, function () {
                        
                        slide.r();
                        
                    });
                    
                },
                r : function () {
                    
                    if( $ul.position().left > 0 || $ul.position().left < -ul_max_width ) {
                        
                        $ul.css({ left : 0 });
                        
                    }
                    
                }
                
            };
        
        $ul.css({ width : ul_max_width });
        
        $f.click(function () {
            
            remaining = ul_max_width - Math.abs( $ul.position().left );
            
            if ( remaining > ul_min_width ) {
                
                slide.f();
                
            }
            
        });
        
        $b.click(function () {
            
            if ( $ul.position().left !== 0 ) {
                
                slide.b();
                
            }
            
        });
        
    };
    
} (RX) );

// Implementation

(function (region) {
    
    "use strict";
    
    $(window).load(function () { region.collapseHeader(this); });
    
    $(window).resize(function () { region.collapseHeader(this); });
    
    $(document).ready(function () {
            
        // Global
            region.tooltip.init();
            region.add_this();
            region.rel_external();
            region.slideshow();
        
        // Contact Page
            region.contact();
            
        // Contact & Donate Page
            region.form_select();
        
        // Donate Page
            region.radio_select();
        
        // Widgets
            region.press_slider();
            region.map.init();
            region.gallery_slider();
            region.quotes();
            region.tweet('rxartinc');
            
        // Store
            region.store_slideshow();
            region.single_choice();
            region.multiple_choice();
            region.checkbox();
        
        // View Select
            region.view_select();
        
        // Blog
            region.category_select();
        
        // Overlabel
            //region.overlabel('#register','#coupon','#checkout','#donate');
      //donate notes
        
      $('#donate').bind('submit', function(){
      var name = $('#honorary_name').val(),
          msg = $('#message').val(),
          cause = $('#donate-subject').val();
      $('#notes').val(cause+ ' = ' +name+' = '+msg);
 
      });
   
      // Store : Same As
            $('#sameAs').click(function() {
              $('#shipping input:not(#sameAs)', ':visible', document.body).each(function(i) { 
                if($('#billing input').eq(i).val() != '') {
                  $(this).focus().val($('#billing input').eq(i).val()).blur();
                }
                
                //fetch select values
                var billCountry = $("#billing_country").val();
                var billState = $("#billing_state_US").val();
                //set select values
                $("#shipping_country").val(billCountry);
                $("#shipping_state_US").val(billState);  
        
              }); 
              return false; 
            });          

    });
    
} (RX) );

