APP = {
    'Car': json.car,
    callback: function () {

    },
    callbackLater: function () {
        if (APP.CardSet.expanding) {
            setTimeout('APP.callbackLater()',500);
        } else {
            APP.callback();
            APP.callback = function () {

            };
        }
    },
    'CarBanner': {
        images: json.car.bannerImages,
        current: 0,
        start: function() {
            APP.CarBanner.timer = setInterval(APP.CarBanner.next, 5000);
        },
        next: function() {
            $('#ImgLoader img').fadeOut(250, function() {
                var img = new Image();
                $(img)
                  .load(function () {
                    $(this).hide();
                    $('#ImgLoader')
                      .removeClass('loading')
                      .html('')
                      .append(this);
                    $(this).fadeIn(300);
                  })
                  .error(function () {
                    // notify the user that the image could not be loaded
                  })
                  .attr('src', 'images/'+APP.CarBanner.images[APP.CarBanner.current]);
            });
            APP.CarBanner.current += 1;
            if (APP.CarBanner.current >= APP.CarBanner.images.length) {
                APP.CarBanner.current = 0;
            }
        }
    }
};

JI = {
    MCInit: function (list) {
        this.cards = [];
        this.elements = list;

        for (var x = 0; x < list.length; x +=1) {
            this.cards.push(new JI.Card({'q':x+1, 'el':$(this.elements[x]), 'parent': this.cards }));
            var el = $(this.elements[x]);
            var posLeft = $(el).position().left;
            var posTop = $(el).position().top;
            var theCss = {'left': posLeft+'px', 'top': posTop+'px'};
            $(el).wrapInner('<div class="liWrap">').animate(theCss, 200, function() {
                $(this).css('position','absolute');
            });
        }

        this.CardSet = new JI.CardSet(this.cards);
        if (document.location.hash.split('/')[1]) {
            this.CardSet.init(document.location.hash.split('/')[1]);
        } else {
            this.CardSet.init();
        }

        this.cards = null;

        return this.CardSet;
    },
    Card: function(args) {
        if (typeof args == 'object') {
            var name;
            for (name in args) {
                this[name] = args[name];
            }

            this.zero = function () {
                this.resize(1,1);
                // $(this.el).css('opacity',0.65);
				$(this.el).addClass('closed');
            };
            this.init = function () {
                this.resize(1,1);
                //this.moveToQuadrant(this.q, 200);
				 this.moveToQuadrantCenter(this.q, 200);
				$(this.el).removeClass('closed');

            };
            this.moveToQuadrant = function (quadrant, speed, delayVal, isExpanding) {
                this.newQ = quadrant;
                var pos = this.getPosition(this.newQ);
                this.newX = pos.x;
                this.newY = pos.y;
                if (speed === undefined) {
                    speed = 300;
                }
                if (delayVal === undefined) {
                    delayVal = 0;
                }
                isExpanding = true;
                if (!(isExpanding)) {
                    $(this.el).delay(delayVal).animate({top:0, left:0}, 200, 'easeInExpo').delay(200).animate({'top': this.newY, 'left': this.newX}, speed, 'easeOutQuint');                
                } else {
                    $(this.el).delay(delayVal).delay(200).animate({'top': this.newY, 'left': this.newX}, speed, 'easeOutQuint');
                }

            };
            this.moveToQuadrantCenter = function (quadrant, speed, delayVal, isExpanding) {
                this.newQ = quadrant;
                var pos = this.getPosition(this.newQ);
                this.newX = pos.x + 102;
                this.newY = pos.y;
                if (speed === undefined) {
                    speed = 300;
                }
                if (delayVal === undefined) {
                    delayVal = 0;
                }
                isExpanding = true;
                if (!(isExpanding)) {
                    $(this.el).delay(delayVal).animate({top:0, left:0}, 200, 'easeInExpo').delay(200).animate({'top': this.newY, 'left': this.newX}, speed, 'easeOutQuint');                
                } else {
                    $(this.el).delay(delayVal).delay(200).animate({'top': this.newY, 'left': this.newX}, speed, 'easeOutQuint');
                }

            };
            this.moveRight = function (times) {
                if (times === undefined) {
                    times = 1;
                } 
                if (this.newQ) {
                    this.newQ += times;
                } else {
                    this.newQ = this.q + times;
                }              
                this.moveToQuadrant(this.newQ);
                if (this.parent[this.q]) {
                    this.parent[this.q].moveRight();                
                }
            };
			
			//***** ek-nav adjust -
			
            this.getPosition = function (quadrant) {
                var yMultiplier = 260;
                var xMultiplier = 202; // 202
                var x, y;

                if (quadrant % 5 == 0) {
                    x = 4 * xMultiplier;
                    y = (parseInt(quadrant/5,10) - 1) * yMultiplier;
                } else {
                    x = ((quadrant % 5) - 1) * xMultiplier;
                    y = parseInt(quadrant/5,10) * yMultiplier;
                }
                return {'x':x,'y':y};
            };
            this.clicked = function(event) {
                if (APP.CardSet.expanding) {

                } else {
					$('.closeBtn').remove();
                    window.location.hash = '/'+APP.CardSet.getKey(event.data.q);
                    APP.CardSet.expand([event.data.q]);
                }

            };
            this.resize = function (width, height) {
                var newWidth = 193 + (Math.ceil((width-1) * 193)) + (9 * (width - 1));
                var newHeight = 250 + (Math.ceil((height-1) * 250)) + (10 * (height - 1));
                // css('z-index',  99)
				// $('.expanded .cardFrame').hide();
                if (!((width == 1)&&(height == 1))) {
					$('.expanded .cardFrame').hide();
                    var selector;
                    var section = APP.Car.sections[this.q-1];
                    var scrollbarSections = APP.Car.scrollbarSections;
                    $.each(scrollbarSections, function(idx,val) {
                       if (val == section.key)  {
                           selector = '#' + section.key + ' .contentBody';
                       }
                    });
                    
                    APP.callback = function () {
                        if (section.key == 'merchandise') {
                            $(selector).width(function(index, width) {
                                return width - 10;
                            }).height(340);
                        } else if (section.key == 'membersclub') {
                            $(selector).width(function(index, width) {
                                return width - 10;
                            }).height(350);                            
                        }
						if ($.browser.msie) {
                            $(selector).css({'opacity':'','overflow-x':'hidden'}).addClass('scrollbars');
                        } else {
							$(selector).jScrollPane({scrollbarWidth:14});
                   		}
						$('.expanded .cardFrame').hide();
                        // $('table tr td:nth-child(1):not(form *)').css({'text-align':'left', 'font-weight': 'bold'});
                        // $('table tr:nth-child(odd) td:not(form *)').css('background', '#e1e1e1');
                    };
                    APP.callbackLater();
					$(this.el).find('div.cardFrame').hide();

                    var html = $.ajax({
                      // url: APP.Car.sections[this.q-1].content + '?' + Math.ceil((Math.random()*1000)),
                      url: APP.Car.sections[this.q-1].key + ".htm",
                      async: false
                     }).responseText;
                    $(this.el).find('.contentFrame').fadeOut(0, function() {
                        //Stuff to do *after* the animation takes place;
                        $(this).html(html).parent().parent()
								.removeClass('closed')
                                .addClass('expanding expanded')
                                .find('.cardFrame')
                                .hide()
                                .end()
                                .css({'z-index': 99, 'opacity':1}).delay(300)
                                .animate({'width':newWidth,'height':newHeight}, 300, 'easeInBack', function () {
                                    $(this).removeClass('expanding').css('opacity',1).find('.contentFrame').fadeIn(0, function () {
                                        // .find('.contentBody').css({'height':newHeight-35, 'width': newWidth}).end()
										$('.closeBtn').remove();
                                        $(this).append('<div class="closeBtn"><a href="javascript:APP.CardSet.init();">Close</a></div>');

                                        APP.CardSet.expanding = false;
                                    });
                            });
						$('.expanded .cardFrame').hide();
                    });                

                    $('#cardContainer').addClass('opened');
                } else {

                    if ($(this.el).attr('class') == 'expanded') {

                        $(this.el)
                            .find('.contentFrame').css({'height':'', 'width':''}).html('').end()
                            .removeClass('expanded').addClass('expanding');

                        ease = 'easeInExpo';
                    } else {
                        ease = 'easeOutCirc';
                    }

                    $(this.el).delay(100).animate({'width':newWidth,'height':newHeight}, 300, ease, function() {
                        $(this).css({'z-index':''})
                        .removeClass('expanding')
                        /*.css('opacity',0.65)*/.find('.cardFrame').show();
                    });


                }
                return this;            
            };

            //init
            if (this.q !== undefined) {
                var pos = this.getPosition(this.q);
                this.x = pos.x;
                this.y = pos.y;
            }
            if (this.el !== undefined) {
                $(this.el).find('.cardFrame').bind('click.box'+this.q, this, this.clicked);
            };
            return this;
        } else {
            return undefined;
        }
    },
    CardSet: function (args) {
        function oc(a) {
          var o = {};
          for(var i=0;i<a.length;i++) {
            o[a[i]]='';
          }
          return o;
        }
        function getQsUsed(q, w, h) {
            var arr = [];
            var qq = q;
            var x, y;
            for (y = 1; y <= h; y += 1) {
                for (x = 1; x <= w; x += 1) {
                    arr.push(qq);
                    qq += 1;
                }
                qq = qq + 5 - w;
            }
            return arr;
        }
        this.expanding = false;
        this.Cards = args;
        this.zero = function () {
            for (var x = 0; x < this.Cards.length; x += 1) {
                this.Cards[x].zero();
            }
        };


        this.expand = function (card) {
            // this.zero();
            if (card != undefined) {
                this.expanding = true;
                var othersArray = [];
                var ss = APP.Car.sections[card-1];
                var avoidArray = getQsUsed(ss.qExp, ss.width, ss.height);
                for (var x = 0; x < this.Cards.length; x += 1) {
                    if (x != (card-1)) {
                        othersArray.push(x);
                    }
                }
                var qNew = 1;
                for (x = 0; x < othersArray.length; x += 1) {
                    if (qNew in oc(avoidArray)) {
                        while (qNew in oc(avoidArray)) {
                            qNew += 1;
                        }
                    }
                    this.Cards[othersArray[x]].zero();
                    this.Cards[othersArray[x]].moveToQuadrant(qNew, 500, 5);
                    qNew += 1;
                }

                var lastQ = this.Cards[0].getPosition(qNew-1);
                var maxHeight;
                // exception for height
                
                card = '' + card + '';
                switch(card) {
                    case "3":
                    maxHeight = lastQ.y + 220 + 260 + 220;
                    break;
                    case "2":
                    maxHeight = lastQ.y + 220 + 260 + 110;
                    maxHeight += 220;
                    break;
                    default:
                    maxHeight = lastQ.y + 220 + 260;
                    break;
                }
                // if ((card == 2) || (card == 3)) {
                //     maxHeight = lastQ.y + 220 + 360 + 220;
                // } else {
                //     
                // }
                $('#cardContainer').delay(500).animate({'height':maxHeight},'fast');
                this.Cards[card-1].moveToQuadrant(APP.Car.sections[card-1].qExp, 300, 0, true);
                this.Cards[card-1].resize(APP.Car.sections[card-1].width,APP.Car.sections[card-1].height);   
            }

        };

        this.getKey = function(card) {
            if (card <= APP.Car.sections.length) {
                return APP.Car.sections[card-1].key;
            } else {
                return undefined;
            }
        };
        this.getCard = function (tag) {
            var card = undefined;
            $.each(APP.Car.sections, function (idx, val) {
               if (tag == val.key) {
                   card = val.q;
               }
            });
            return card;
        };

        this.init = function (hash) {
			$('.closeBtn').remove();
            for (var x = 0; x < this.Cards.length; x += 1) {
                this.Cards[x].init();
            }

            $('#cardContainer').delay(500).animate({'height':APP.Car.initHeight},'fast', function () {
                if (hash !== undefined) {
						$('#cards li:eq('+parseInt((APP.CardSet.getCard(hash) - 1),10)+') .cardFrame').hide();
						console.log('#cards li:eq('+parseInt((APP.CardSet.getCard(hash) - 1),10)+') .cardFrame');
                        APP.CardSet.expand(APP.CardSet.getCard(hash));
						$('#cards li:eq('+parseInt((APP.CardSet.getCard(hash) - 1),10)+') .cardFrame').hide();
                    }
                    else {
                        $('ul#cards li').delay(500).css('opacity',1);
                        window.location.hash = '/';
                    }    
            }).removeClass('opened');
        };
		this.expandHash = function(hash) {
			APP.CardSet.expand(APP.CardSet.getCard(hash));
		};

    }
    
};

jQuery(function($){
	MMSGNav.init("ralliart");
    APP.CardSet = new JI.MCInit($('ul#cards li'));
    if (!Modernizr.borderradius) {
        $('ul#cards li .liWrap').append('<div class="tl"></div><div class="tr"></div><div class="bl"></div><div class="br"></div>');   
    }
   
    // APP.CardSet.init();
    APP.CarBanner.start();
    // $('.opened ul#cards li:not(.expanded, #MercMenu li, #membersclub li)').live('mouseover mouseout', function(event) {
    //     if (event.type == 'mouseover') {
    //         $(this).css('opacity',1);
    //     } else {
    //         $(this).css('opacity',0.65);
    //     }
    // });

	$(window).hashchange( function(){
		// var hash = window.location.hash;
		// if ((hash.split("/")[1] == "merchandise") && (hash.split("/")[2] !== undefined)) {
		// 	
		// } else {
		// 	APP.CardSet.expandHash(document.location.hash.split('/')[1]);
		// }
	});

});
