// Frame Edge
(function($) {
    $.fn.frameEdge = function(options, defaults) {
        var defaults = {
            background: 'blue',
            width: 10,
            position: 'right '

        };
        var options = $.extend({},
        defaults, options);
        $(this).each(function() {
            var $this = $(this);
            var y = $this.outerHeight();
            var style = {};
            style.background = options.background;
            style.width = options.width
            style.height = y;
            style.position = 'absolute';
            style.top = 0;
            if (options.position == 'right') {
                style.right = -options.width;

            } else {
                style.left = -options.width;

            }
            $this.append('<div class="frameEdge" />');
            $this.find('.frameEdge').css(style);

        });
        return this;

    }

})(jQuery);
// Setbounds
 (function($) {
    $.fn.setBounds = function(options, defaults) {
        var defaults = {
            bound: window,
            outer: '#outer',
            wrapper: '#wrapper'

        };
        var options = $.extend({},
        defaults, options);

        var container = {};
        container.elem = this;
        container.y = $(container.elem).outerHeight();
        container.x = $(container.elem).outerWidth();
        container.position = $(container.elem).position();

        var bound = {};
        bound.elem = options.bound;
        bound.y = $(bound.elem).height();
        bound.x = $(bound.elem).width();

        var dif = {};
        dif.y = container.y - bound.y;
        dif.x = container.x - bound.x;

        var wrapper = {};
        wrapper.elem = options.wrapper;
        wrapper.y = container.y + dif.y;
        wrapper.x = container.x + dif.x;

        $(this).each(function() {
            $(wrapper.elem).css({
                'position': 'absolute',
                'height': wrapper.y,
                'width': wrapper.x,
                'left': -dif.x,
                'top': -dif.y

            });
            $(container.elem).css({
                'marginTop': dif.y,
                'marginLeft': dif.x

            });
            $(options.outer).css({
                'height': bound.y,
                'width': bound.x

            });


        });

        function increment(direction) {
            var container = {};
            container.elem = '#container';
            container.y = $(container.elem).outerHeight();
            container.x = $(container.elem).outerWidth();
            container.position = $(container.elem).position();

            switch (direction) {
                case 'up':
                if ( - (wrapper.y - container.y) >= container.position.top) {
                    return;

                } else {
                    $(container.elem).animate({
                        "top": "-=150px"
                    }, 0);

                }
                break;
                case 'right':
                if ( - (wrapper.x - container.x) >= container.position.left) {
                    return;

                } else {
                    $(container.elem).animate({
                        "left": "-=150px"
                    }, 0);

                }
                break;
                case 'down':
                if (container.position.top >= 0) {
                    return;

                } else {
                    $(container.elem).animate({
                        "top": "+=150px"
                    }, 0);

                }
                break;
                case 'left':
                if (container.position.left >= 0) {
                    return;

                } else {
                    $(container.elem).animate({
                        "left": "+=150px"
                    }, 0);

                }
                break;
                default:
                return;

            }

        }

        // Controller Arrows
        $('#directionalController a').css('opacity', 0.75);
        $('#directionalController a').hover(function() {
            $(this).stop().fadeTo(500, 1);

        },
        function() {
            $(this).stop().fadeTo(500, 0.75);

        });
        $('a.moveUp, a.moveDown').css({
            'left': (bound.x - 64) / 2

        });
        $('a.moveLeft, a.moveRight').css({
            'top': bound.y / 2

        });

        $('a.moveUp').click(function() {
            increment('down');

        });
        $('a.moveRight').click(function() {
            increment('right');

        });
        $('a.moveDown').click(function() {
            increment('up');

        });
        $('a.moveLeft').click(function() {
            increment('left');

        });

        // Key Bindings
        $(document).bind('keydown', 'up', 
        function() {
            direction = 'down';
            increment(direction);
        });
        $(document).bind('keydown', 'right', 
        function() {
            direction = 'right';
            increment(direction);
        });
        $(document).bind('keydown', 'down', 
        function() {
            direction = 'up';
            increment(direction);
        });
        $(document).bind('keydown', 'left', 
        function() {
            direction = 'left';
            increment(direction);
        });


        return this;

    }

})(jQuery);
// Move Container
 (function($) {
    $.fn.moveContainer = function(options, defaults) {
        var $this = $(this);
        var defaults = {
            target: this,
            event: 'click',
            duration: 600,
            padding: {
                top: 20,
                left: 20

            },
            container: '#container',
            wrapper: '#wrapper',
            after: function() {}

        };
        var options = $.extend({},
        defaults, options);
        var container = {};
        container.elem = options.container;
        container.x = $(container.elem).outerWidth();
        container.y = $(container.elem).outerHeight();
        container.position = $(container.elem).position();

        var target = {};
        target.elem = options.target;
        target.offset = $(target.elem).offset();
        $this.each(function() {
            $this.bind(options.event, 
            function() {
                var win = {};
                win.elem = window;
                win.x = $(win.elem).width();
                win.y = $(win.elem).height();
                var end = {};
                if (target.offset.top - options.padding.top < 0) {
                    // Target element is already on the edge
                    end.top = 0;

                } else if ((win.y + target.offset.top) > container.y) {
                    end.top = win.y - container.y;

                } else {
                    end.top = -target.offset.top + container.position.top + options.padding.top;

                }
                if (target.offset.left == 0) {
                    // Target element is already on the edge   
                    end.left = 0;

                } else if ((win.x + target.offset.left) > container.x) {
                    end.left = win.x - container.x;

                } else {
                    end.left = -target.offset.left + container.position.left + options.padding.left;

                }
                $(container.elem).animate({
                    'top': end.top,
                    'left': end.left

                },
                options.duration, 'easeInOutCirc');

                setTimeout(options.after, options.duration * 2);

                return false;

            });

        });

        return this;

    }

})(jQuery);
// Set Background
function setBackground(horzImg, vertImg) {
    $('#header').append('<div class="rule" />');
    $('#container').append('<div class="pseudoHeader" />')
    $('#header .rule, #container, #wrapper, body, .pull.north.east, .lightBox').css({
        background: 'url(' + horzImg + ')'

    });
    if (vertImg != undefined && jQuery.fn.frameEdge) {
        $('body.drag .section:not(.end, .right), body.drag .contentBlock:not(.end, .right), body.drag .grouping:not(.end, .right)').frameEdge({
            background: 'url(' + vertImg + ')  -10px 0',
            position: 'right'

        });
        $('body.drag .pull.north.east').frameEdge({
            background: 'url(' + vertImg + ') -10px 0',
            position: 'left'

        });


    }

};
//  Init Movement
function initMovement(elem, target, after) {
    var paddingTop = $('#header').height();
    var opts = {};
    opts.target = target;
    opts.padding = {};
    opts.padding.top = paddingTop + 20;
    opts.padding.left = 20;
    opts.after = after;
    $(elem).moveContainer(opts);

};
//  INit Cycle
function initCycle(elem, type) {
    if (type == 'thumbs') {
        var id = $(elem).parents('.section').attr('id');

    } else if (type == 'lightbox') {
        var id = $(elem).parents('.lightBox').attr('id');

    }

    var opts = {};
    opts.fx = 'shuffle';
    opts.speed = 250;
    opts.easing = 'easeOutBack'
    opts.timeout = 0;
    opts.pager = '#' + id + ' .thumbs ul';
    opts.pagerAnchorBuilder = buildPager;

    function buildPager(idx, slide) {
        return '#' + id + ' .thumbs ul li:eq(' + idx + ') a';

    };

    if (jQuery.fn.cycle) {
        $(elem).cycle(opts);

    } else {
        return;

    }

};
// Init AddCart
function initItem() {
    // Additional Colors
    $('.addColor a').click(function() {
        target = $(this).attr('href'); 
        $.fancybox.close();
        setTimeout(function() {
            $(target).find('a.box').trigger('click');
        },
        800);
        return false;
    });

    
    $('.item-pic').cycle();
    //  Setsup Selectbox 
    $('.addCartForm select').selectbox();

};


//  Document Ready
$(document).ready(function() {
    
    // external links
  	$('a[rel=external]').click(function(){
  		window.open(this.href);
  		return false;   
  	});
    
    $('#outer').append('<div id="mousehelper" />').mousemove(function(e) {
      $('#mousehelper').show().css({
        top: e.pageY - 15,
        left: e.pageX + 15
      });
    });
    
    $('#header, #directionalController a').hover(function(){
      $('#mousehelper').hide();
    }, function(){
      $('#mousehelper').show();
    });
    
    $('.help').fancybox({
      showCloseButton: true,
      padding: 0,
      hideOnContentClick: true
    });
 
    // Instructions
     if($.cookie('hi')) {
       
     } 
     else{
       var options = { path: '/', expires: 10 };
        $.cookie('hi', '1', options);
        $('.help').trigger('click');       
     }
    // Slide Shows
    initCycle('.slide', 'thumbs');
    // Click Helpers + mask
    $('.contentBlock, #store li').each(function() {
        //$(this).append('<span class="helper nw" /><span class="helper ne" /><span class="helper se" /><span class="helper sw" />');
        $(this).has('a.box').append('<div class="mask" />');
        $('body:not(.checkout)').find('.mask').hide();

    });
    // Draggable
    function startDrag() {
        $('body:not(.checkout) .mask').show();
    }
    function stopDrag() {
        $('body:not(.checkout) .mask').hide();

    }
    $('body.drag #container').setBounds().draggable({
        cursor: 'move',
        containment: 'parent',
        start: startDrag,
        stop: stopDrag

    });
    // Main Nav Click
    $('body.drag #header a:not(.viewCart, .remove)').each(function() {
        var $this = $(this);
        var title = $this.attr('title');
        var x = $this.find('img').width();
        var html = '';

        html += '<div class="tt">';
        html += title;
        html += '</div>';

        var $tt = $this.find('>div.tt');

        elem = $this;
        target = $this.attr('href');
        initMovement(elem, target);

        $this.hover(function() {
            $this.append(html);
            $this.find('>div.tt').css({
                'left': -(300 - x) / 2

            });

        },
        function() {
            $this.find('>div.tt').remove();

        });


    });

    //  Hovers
    $('.contentBlock>a.box, #store li>a.box').each(function() {
        var $this = $(this);

        var x = $this.parents('.contentBlock').width();
        var y = $this.parents('.contentBlock').height();
        var style = $this.attr('class').split(' ').slice(1, -1);
        var color = $this.attr('class').split(' ').slice(-1);
        
          if((color == '' ) || (color == null)){
            $(this).addClass('transparent');
            var color = $this.attr('class').split(' ').slice(-1);
          }
        //console.log(color)
        // Add Hover Helper 
        $this.prepend('<div class="hover" />');
        var $hover = $this.find('>div.hover');
        $hover.css({
            'background': color,
            'opacity': 0.5
        });
        //  Hide Hover Helper
        if (style == 'fade' || style == 'featured') {
            $hover.hide().css({
              'height' : y,
              'width' : x
            })
            $this.hover(function() {
                $hover.stop().fadeTo(500, 0.5);

            },
            function() {
                $hover.stop().fadeTo(500, 0);

            });

        } else if (style == 'sweep-down') {
            $hover.css({
                'height': 0,
                'width': x

            });
            $this.hover(function() {
                $hover.stop().animate({
                    'height': y

                });

            },
            function() {
                $hover.stop().animate({
                    'height': 0

                });

            });

        } else if (style == 'sweep-up') {
            $hover.css({
                'height': 0,
                'width': x,
                'marginTop': y

            });

            $this.hover(function() {
                $hover.stop().animate({
                    'height': y,
                    'marginTop': 0

                });

            },
            function() {
                $hover.stop().animate({
                    'height': 0,
                    'marginTop': y

                });

            });


        } else if (style == 'sweep-right') {
            $hover.css({
                'height': y,
                'width': 0

            });
            $this.hover(function() {
                $hover.stop().animate({
                    'width': x

                });

            },
            function() {
                $hover.stop().animate({
                    'width': 0

                });

            });

        } else if (style == 'sweep-left') {
            $hover.css({
                'height': y,
                'width': 0,
                'marginLeft': x

            });

            $this.hover(function() {
                $hover.stop().animate({
                    'right': 0,
                    'width': x,
                    'marginLeft': 0

                });

            },
            function() {
                $hover.stop().animate({
                    'right': 0,
                    'width': 0,
                    'marginLeft': x

                });

            });


        }



    });



    // Light Boxes
    $('a.box, .viewCart').each(function() {
        var type = $(this).attr('rel');
        var opts = {};
        opts.overlayColor = '#6c9';
        opts.padding = 0;
        opts.cyclic = true;
        opts.autoScale = false;
        opts.onStart = function() {
          $('#mousehelper').hide();
        };
        opts.onClose = function() {
           $('#mousehelper').show();
        }
        if (type == 'artist-wanted slideshow') {
            opts.onComplete = function() {
                initCycle('.artist-wanted .slideShow', 'lightbox');

            };
            opts.autoDimensions = false;
            opts.scrolling = 'no';
            opts.height = 690;
            opts.width = 950;

        }
        if (type == 'store') {
            opts.onComplete = initItem;

        }
        if (type == 'cart') {
            opts.scrolling = 'no';
            opts.width = 900;
            opts.onComplete = function() {
                $.getScript('/includes/js/freecity.cart.js');

            };

        }
        $(this).fancybox(opts);

    });



    // Lightbox Controls
    $('.lightboxControls a').live('click', 
    function() {
        var action = $(this).attr('class');
        switch (action) {
            case 'close':
            $.fancybox.close();
            break;
            case 'next':
            $.fancybox.next();
            break;
            case 'prev':
            $.fancybox.prev();
            break;
            default:
            return;

        }

    });

    // Buy Button Ajax Cart
    function miniAdd() {
        var thumbSrc = $('.item-pic img:first').attr('src'),
            thumbDesc = $('.item-pic img:first').attr('alt');

        var $miniCart = $('#minicart ul.items'),
        cartX = $miniCart.width();

        var $form = $(this).parents('.addCartForm form');
        var data = $form.serialize();
        var id = $form.find('#size').val();
        //var option = $form.find('#size').val();
        var thumb = {};
            thumb.large = '<li id="item-'+id+'"><img src="' + thumbSrc + '" alt="' + thumbDesc + '" height="60" /></li>';
            thumb.small = '<li id="item-'+id+'"><img src="' + thumbSrc + '" alt="' + thumbDesc + '" height="35" /></li>';

        
        function request(){
          $.ajax({
            type: 'POST',
            url: 'add_to_cart.php',
            data: data,
            success: function() {
                if($('#minicart #item-'+id).length) {
                  return;
                } else {
                  if ($miniCart.length) {
                      if (cartX >= 370 || $miniCart.hasClass('small')) {
                          $miniCart.addClass('small').find('img').height(35);
                          $('#minicart ul.items').append(thumb.small);
                      } else {
                          $('#minicart ul.items').append(thumb.large);
                      }
                  }
                }
            }
          });     
        }
      
      //Check Size Select  
        if($('#size_container').length) {
          if($('span.error').length) {
            return false;
          } 
          else {
            if($('#size_input_none').hasClass('current_value')) {
              $('#size_container').append('<div class="error">PLEASE SELECT A SIZE<br/>THEN CLICK BUY IT</div>');
              return false;
            } 
            else {
              request();
            }
          }
        } 
        else {
          request();
        }
        $.fancybox.close();

        return false;

    };
    
    //Remove Error
    $('#size_container li').live('click', function(){
       $('.error').remove();
    });
    
    function miniRemove() {
        var $this = $(this);
        var $thumb = $this.parents('li');
        $thumb.fadeTo(500, 0);
        setTimeout(function() {
            if ($('#minicart li').length == 7) {
                $('#minicart').find('img').css('height', 80).end().find('ul').removeClass('small');

            }
            $thumb.remove();

        },
        500);
        return false;

    }
    $('.addCartForm .submit input').live('click', miniAdd);
    // $('#minicart a.remove').live('click', miniRemove);



});
$(window).bind('resize', 
function() {
    $('body.drag #container').setBounds();

});
