var Navigation = {
	lastImg: false,
	hiddenImgSrc: false,
	open: false,
	
	showMouseOverImg: function(img) {
		Navigation.hiddenImgSrc = img.src;
		img.src = '/img/nav/' + img.alt + '_over.gif';
	},

	hideHoveredImage: function(img) {
		if (Navigation.hiddenImgSrc) {
			img.src = Navigation.hiddenImgSrc;
		}
	},

	selectTab: function(id) {
		if ($(id + 'Img')) {
			$(id + 'Img').src = '/img/nav/' + id + '_selected.gif';
		}
	},

    getNavElements: function(name, after){
        new Ajax.Request('/nav/' + name, {
                method: 'get',
                onSuccess: function(list) {
                	$('categories').update(list.responseText);
                	if (after) { after(); }
                }});
    },
    
    loadNavElements: function(html, after) {
    	$('categories').update(html);
    	if (after) { after(); }
    },

    slideMenu: function() {
        new Effect.Move('categories',{ duration: 2.2, delay: 0.3, x: -966, y: 0, mode: 'absolute'});
        new Effect.Move('subCats',{ duration: 2.2, delay: 0.3, x: -966, y: 0, mode: 'absolute'});
        $('amazonNav').setStyle({height: ''});
        Navigation.slide = true;
    },

    slideBack: function() {
        new Effect.Move('categories',{ duration: 2.2, delay: 0, x: 0, y: 0, mode: 'absolute'});
        new Effect.Move('subCats',{ duration: 2.2, delay: 0.0, x: 0, y: 0, mode: 'absolute', afterFinish: function(){
            $('amazonNav').setStyle({height: '80px;'});
        }});
        Navigation.slide = false;
    }
};

var Page = {
    replacementDiv: false,
    openDiv: false,
    allow: true,
    clicked: false,
    searchIndex: null,

     getStorefront: function(){
        new Ajax.Request('/store/index', {
            method: 'get',
            onSuccess: function(flash) {
            	var childElements = $('fillme').childElements();
            	childElements.each(function(element) {
            		element.remove();
            	});
                $('fillme').insert({top:new Element('div', {id: 'main', className: 'section'})});
                $('main').insert(new Element('div', {id: 'flash'}).update(flash.responseText));
            }
        });
        s.pageName = 'Store';
    },

    getCatItems: function(catId, searchIndex){
    	this.searchIndex = searchIndex;
        Page.getSubCategories(catId);
        Page.getItemsPage(catId, 1);

    },

    getItemsPage: function(nodeId, page){
        if(Page.allow){
            Page.allow = false;
        	Page.replacementDiv = nodeId+''+page;
        	new Ajax.Request('/store/ajaxSearch/' + nodeId + '/' + page + '/' + this.searchIndex, {
        		method: 'get',
        		onSuccess: function(store) {
		            $('fillme').update(store.responseText);
		            if(page == 1 && store.responseText.indexOf('We did not find any matches') == -1){ Page.addScroller(nodeId);}
		            if(store.responseText.indexOf('We did not find any matches') != -1){$('scrollBdy').setStyle('display:none;');}
		            Page.allow = true;
            	}
        	});
        }
    },

    addScroller: function(nodeId) {
        new Ajax.Request('/store/scroller/' + nodeId + '/' + this.searchIndex, {
        method: 'get',
        onSuccess: function(scroller) {
            $('scrollContainer').setStyle('display: block;');
            $('scrollContainer').update(scroller.responseText);
            $('scrollNodeId').update(nodeId);
            }
        });
    },

     getSubCategories: function(nodeId){
        new Ajax.Request('/nav/getSubCatList/' + nodeId, {
                method: 'get',
                onSuccess: function(subCats) {
                $('subs').update(subCats.responseText);
                Navigation.slideMenu();
                if(nodeId == 283155 || nodeId == 130){
                    $('slideBack').setStyle('height: 120px;')
                }
                else
                {
                    $('slideBack').setStyle('height: 80px;')
                }
                }});
    },

    toggleInfo: function(element) {
        var togg = Element.childElements(element);
        var div = Element.nextSiblings(element);


        if(!Page.clicked){
            Page.clicked = true;
            if(togg[0].id == 'first'){
                togg[0].id = '';
                togg[0].src = '/img/arrow_right.gif';
                togg[0].alt = 'arrow_right';
                new Effect.toggle(div[0].id, 'blind', {duration: 0.5, afterFinish: function(){Page.clicked = false;}});
            }else{
                Page.images = $$('div.faqContent div.faqTitle img[src$=gif]');
                Page.images.each(function(img){
                if(img.alt == 'arrow_down') {
                   var toClose = img.up().nextSiblings();
                   new Effect.toggle(toClose[0].id,'blind', {duration: 0.5, afterFinish: function(){Page.clicked = false;}});
                   img.src = '/img/arrow_right.gif';
                   img.alt = 'arrow_right';
                   img.id='';
                }
                });

                if(Page.openDiv != element) {
                    togg[0].src = '/img/arrow_down.gif';
                    togg[0].alt = 'arrow_down';
                    new Effect.toggle(div[0].id, 'blind', {duration: 0.5, afterFinish: function(){Page.clicked = false;}});
                }
            }

            if(Page.openDiv == element){
                Page.openDiv = false;
            }else{
                Page.openDiv = element;
            }
        }
    },

	newToggle: function(id) {
		var element = $('toggle' + id);
		
		if (!Page.clicked && element) {
			Page.clicked = true;
			var img = $('img' + id);

			if (element.style.display == 'none') {
				img.src = '/images/arrow_down.png';
				img.alt = 'arrow_down';
				img.height = 9;
			} else {
				img.src = '/images/arrow_up.png';
				img.alt = 'arrow_up';
				img.height = 15;
			}

			new Effect.toggle(element, 'blind', {duration: 0.5, afterFinish: function() {Page.clicked = false;}});
		}
	},

	showNext: function(id) {
		id = array_search(Math.abs(id), qArray);
		id = Math.abs(id) + 1;
		id = qArray[String(id)];
		var element = $('toggle' + id);

		if (!Page.clicked && element) {
			var img = $('img' + id);

			if (element.style.display == 'none') {
				Page.clicked = true;
				img.src = '/images/arrow_down.png';
				img.alt = 'arrow_down';
				img.height = 9;
				new Effect.toggle(element, 'blind', {duration: 0.5, afterFinish: function() {Page.clicked = false;}});
			}
		}
	},

    getStaticPage: function(element, title){
        if(Page.allow){
            Page.allow = false;
            new Ajax.Request(element.id, {
                method: 'get',
                onSuccess: function(page) {
                    $('fillme').update(page.responseText);
                    $('scrollContainer').setStyle('display: none;');
                    Page.allow = true
                    if(title){
                        document.title = title;
                    }
                }
            });
        }
        s.pageName = title;
    },
    getCreateAccountPage: function() {
        new Ajax.Request('/pages/create_account_form', {
            method: 'get',
            onSuccess: function(page) {
                $('loginBox').update(page.responseText);
            }
        });
        s.pageName = 'create account';
    }
};

var Shopping = {
    updatePrice: function(element, price) {
        var id = element.id.split("_");
        var qty = parseInt(element.value);

        if(!qty || isNaN(qty) || qty == ''){
            return;
        } else {
            if(qty == 0){
                qty = 1;
            }

            $(id[0]+'_qty').value = qty;
            $(id[0]+'_price').update(qty*price);
        }

        Shopping.updateSummery();
        Shopping.updateSessionVars(id[0], qty);
    },

    updateSummery: function() {
        var priceArray = $$('.price')
        var subTotal = 0;

        priceArray.each(function(p) {
           subTotal += parseInt(p.innerHTML);
        });

        if(subTotal > 25){
            total = subTotal;
            shipping = 0;
        }else{
            shipping = Math.ceil(subTotal*.2)
            total = subTotal+shipping;
        }

        $('shipping').update(shipping);
        $('subTotal').update(subTotal);
        $('total').update(total);
    },

    updateSessionVars: function(asin, qty) {
        new Ajax.Request('/shopping_cart/updateSession/' + asin + '/' + qty, {
        method: 'get',
        onSuccess: function(){return;}
        });
    }
};

var Charity ={
    inAction: false,

    donate: function (id){
        if(!Charity.inAction)
        {
            var amount = parseInt($('donationAmount').value);
            if((amount != '' && !isNaN(amount)) && id != '')
            {
                Charity.inAction = true;
                location = '/charity/donate/' + id + '/' + amount;
            }else{
                $('errorMsg').update('You have to donate at least 1 Karma Point');
            }
        }
    }
};

function nextPage(){
    var page = $('pageNumber').innerHTML;
    Page.getItemsPage($('scrollNodeId').innerHTML, page);

    $('pageNumber').update(parseInt(page)+2);
}
function prevPage(){
    var page = $('pageNumber').innerHTML;

    if(page < 3){
        return;
    }

    Page.getItemsPage($('scrollNodeId').innerHTML, page-2);
    $('pageNumber').update(parseInt(page)-2);
}
function jp(catList){
    var imgs = $$('div.navigation div.navList ul#chaseNav li.navItem img[src$=gif]');
    imgs.each(function(img){
        if(img.id == 'store'){
            Navigation.lastImg = img;
            Navigation.lastImg.src = '/img/nav/' + Navigation.lastImg.alt +'_selected.gif';
        }});
    $('amazonNav').setStyle('height: 80px;');
    Navigation.loadNavElements(catList, function() {
    	new Effect.toggle('amazonNav','blind', {afterFinish: function(){$('storeImg').src = '/img/nav/get_selected.gif';}});
    });
}

function getPage(path){
    new Ajax.Request(path, {
                method: 'get',
                onSuccess: function(page) {
                    $('fillme').update(page.responseText);
                    $('scrollContainer').setStyle('display: none;');
                    Page.allow = true
                }
            });
}
function ajaxPage(path, nav) {
	if ($('amazonNav')) {
	    $('amazonNav').setStyle('height: 49px;');
		Navigation.getNavElements(nav, function() {
			new Effect.toggle('amazonNav','blind', {afterFinish: function(){$(nav + 'Img').src = '/img/nav/' + nav + '_selected.gif';}});
		});
	}
	getPage(path);
}
function topPage(nav, catList) {
    $('amazonNav').setStyle('height: 49px;');
    Navigation.loadNavElements(catList, function() {
    	new Effect.toggle('amazonNav','blind', {afterFinish: function(){$(nav + 'Img').src = '/img/nav/' + nav + '_selected.gif';}});
    });
}
var Facebook = {
	logout: function() {
		$('waitScreen').setStyle('display: block;');
		
		// IE bungles dynamically created onload()s for iframes
		// so we have to add it in the createElement!  This is 
		// also  the reason for the clumsy method of modifying 
		// the onload handler in iframeLoaded().

		if (Prototype.Browser.IE) {
			var iframe = document.createElement('<iframe onload="Facebook.iframeLoaded();">');
		} else {
			var iframe = document.createElement('iframe');
			iframe.setAttribute('onload', 'Facebook.iframeLoaded();');
		}
		iframe.setAttribute('id', 'facebookLogout');
		iframe.setAttribute('name', 'logoutFrame');
		iframe.setAttribute('width', 0);
		iframe.setAttribute('height', 0);
		iframe.setAttribute('style', 'position: absolute; z-index: -999; top: -999px; left: -999px;');
		document.body.appendChild(iframe);
		iframe.setAttribute('src', '/login/facebookLogout');
	},
	
	iframeLoaded: function() {
		var iframe = $('facebookLogout');
		if (iframe.contentDocument) {	// DOM
			iframe.contentDocument.getElementById('logoutForm').submit();
		} else if (iframe.contentWindow) {	// IE win
			iframe.contentWindow.document.getElementById('logoutForm').submit();
		}
		// overwriting self...
		Facebook.iframeLoaded = function() {
			location.pathname = '/login/logout';
		};
	}
}

function array_search(needle, haystack) {
	var key = '';

	for(key in haystack){
		if( haystack[key] == needle ){
			return key;
		}
	}

	return false;
}

$$('form').each(function(f) { 
	f.writeAttribute('autocomplete', 'off'); 
});