/**
 * @description Wraps features content with html and shos it in popup
 * @requires PositionedToolTip (global.js)
 */
var FeaturesPositionedPopup = Class.create(PositionedToolTip, {

    initialize: function($super, link, pop, opts) {

        var container = new Element('div', {'class': 'pmpFeature'});
        var content = new Element('div', {'class': 'pmpFeatureContent'});
        container.insert(new Element('h2', {'class': 'pmpFeatureHead'}).update('Features'));
        container.insert(content);
        container.insert(new Element('div', {'class': 'pmpFeatureFt'})
                .insert(new Element('b', {'class': 'arrowLeft'}))
                .insert(new Element('b', {'class': 'arrowRight'}))
        );
        pop.replace(container);
        content.insert(pop.removeClassName('hidden'));
        $super(link, container, opts);
    }

});

/**
 * @description Bundles content paginator
 */
var ContentToggler = Class.create({

    initialize: function(contentElements, contentCallees, options) {
        this.contentElements = contentElements;
        this.contentCallees = contentCallees;
        this.options = options;
        this.currentIndex = 0;
        this.setup();
        this.switchContent(0);
    },

    setup: function() {
        this.contentCallees.each(function(callee, index) {
            callee.observe('click', function(event) {
                event.stop();
                this.switchContent(index);
            }.bind(this));
        }, this);

        $A(this.options.prevBtns).invoke('observe', 'click', function(event) {
            event.stop();
            this.switchContentPrev();
        }.bind(this));

        $A(this.options.nextBtns).invoke('observe', 'click', function(event) {
            event.stop();
            this.switchContentNext();
        }.bind(this));
    },

    switchContent: function(index) {
        if(index > this.contentElements.length -  1) index = 0;
        if(index < 0) index = this.contentElements.length -  1;

        this.contentElements.invoke('addClassName', 'hidden');
        this.contentCallees.invoke('removeClassName', 'selected');
        this.contentElements[index].removeClassName('hidden');
        this.contentCallees[index].addClassName('selected');
        this.currentIndex = index;
    },

    switchContentNext: function() {
        this.switchContent(++ this.currentIndex);
    },

    switchContentPrev: function() {
        this.switchContent(-- this.currentIndex);
    }

});

var check = function(str) {
    return str && /\w/.test(str);
};

var parseLableText = function(label) {
    if(!label) return;
    var html = label.innerHTML.split('|');
    label.innerHTML = html[0];
    if(check(html[1]) && check(html[2])) {
        label.innerHTML += '<span class="oldPrice price">' + html[1] + '</span>';
        label.innerHTML += '<span class="newPrice price">' + html[2] + '</span>';
    } else if(check(html[1])) {
        label.innerHTML += '<span class="price">' + html[1] + '</span>';
    }
};

var log = (function() {
    try {
        return console.log;
    } catch(e) { return function() {}; };
})();

var closeIndexedConfirmDialog = function() {
	$$('div.indexedConfirmDialog').each(function(popup) {
		new Effect.Fade(popup, { duration: .4 });
	});
};

document.observe('pmp:styleDropdowns', function() {

    //Inititalize dropdowns
    // Timeout needed for IE
    setTimeout(function() {
        $$('select.styled').each(function(select) {
            var onch = select.onchange;
            var dropDown = new DropDown(select, {
                onchange: function() {
                    var event = {}; // Fake object as its needed as param for A4J.AJAX.Submit method
                    (function() { onch && onch(event); }).apply(this.hidden);
                }
            });
            // Parse dropdowns text from "productName|oldPrice|newPrice" to productName <span class="price oldPrice">oldPrice</span> <span class="price newPrice">newPrice</span>
            // dropDown.options.each(function(option) { parseLableText(option.select('a').first()); });
            // parseLableText(dropDown.selected.select('a').first());
            dropDown.styled.setStyle({visibility: 'visible'});
        });


        // Parse labels text from "productName|oldPrice|newPrice" to productName <span class="price oldPrice">oldPrice</span> <span class="price newPrice">newPrice</span>
        // Add "selected" class name to checked rows
        $$('table.pmpControls td').each(function(td) {
            var checkbox = td.select('input')[0];
            parseLableText(checkbox.next());
            td.setStyle({visibility: 'visible'});
            if(checkbox.type == 'radio') {
                checkbox.checked ? td.addClassName('selected') : td.removeClassName('selected');
            }
        });


        // Initialize conform popup for bottom section if smth selected in the top
        if($$('div.pmpPopularProgram table.selected').length) {
            $$('.confirmDivClass input[type=radio]',
                    '.confirmDivClass input[type=checkbox]',
                    '.pmpOnlinePrep .selects li').each(function(el){
                new PositionedPopup(el, 'confirmDiv', { popParent: 'div.main', useDefaultEvent: true });
            });

            $$('.pmpTogglePanel select').each(function(select) {
                new PositionedPopup(select, 'confirmDiv', { popParent: 'div.main', useDefaultEvent: true, observers: ['change'] });
            });
        }

    }, 0);

    // Initialize dynamic bundles content toggler
    // log('Inititalize dynamic bundles');
    $$('div.pmpDynamicBundles').each(function(element) {
        var contentElements = element.select('div.pmpBoxTogglingContent');
        var contentCallees = element.select('ul.pmpPager li.pmNumTgl a');
        var paginators = element.select('ul.pmpPager');
        if(contentElements.length > 1) {
            paginators.invoke('setStyle', {visibility: 'visible'});
            setTimeout(function() {
                new ContentToggler(contentElements, contentCallees, {
                    prevBtns: element.select('li.pmpFirst a'),
                    nextBtns: element.select('li.pmpLast a')
                });
            }, 10);
        }
    });

    // Initialize popular programs confirm dialogs
    // log('Initialize popular programs confirm dialogs');
    $$('a.confirmCallee').each(function(callee) {
        callee.removeClassName('confirmCallee');
        new PositionedPopup(callee, 'confirmDiv' + callee.readAttribute('rel'), { popParent: 'div.main' });
    });

    // Initialize pannels togglers
    // log('Initialize pannels togglers');
    $$('.pmpTogglePanelContainer').each(function(container) {
        if(container.hasClassName('pmpTogglePanelInited')) return;
        container.addClassName('pmpTogglePanelInited');
        container.select('div.pmpTogglePanelHandler')[0].observe('click', function(event) {
            event.stop();
            container.toggleClassName('pmpTogglePanelCollapsed');
        });
    });

    // Initialize help tooltips
    // log('Initialize help tooltips');
    $$('.pmpBoxHelp').each(function(handler) {
        var rel = handler.readAttribute('rel');
        var content = $('pmpFeaturedList_' + rel);
        if(rel && rel.length && content) {
            new FeaturesPositionedPopup(handler, content, { yOffset: 20, xOffset: 15, effectOpts: {duration: .2}});
            handler.removeAttribute('rel');
        }
    });

});



document.observe('dom:loaded', function() {
    document.fire('pmp:styleDropdowns');
});



function getPageDimensions() {
    var xWithScroll, yWithScroll;
	if (window.innerHeight && window.scrollMaxY) {// Firefox
		yWithScroll = window.innerHeight + window.scrollMaxY + "px";
		xWithScroll = window.innerWidth + window.scrollMaxX + "px";
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		yWithScroll = document.body.scrollHeight + "px";
		xWithScroll = document.body.scrollWidth + "px";
	} else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
		yWithScroll = document.body.offsetHeight + "px";
		xWithScroll = document.body.offsetWidth + "px";
  	}
  	if(is_gecko) {
		xWithScroll = "100%";
	}

	return [xWithScroll, yWithScroll];
}

function toggleClassDetailsVisibility(element) {
    $(element.parentNode).toggleClassName('pmpProductItemExpanded');
}

function displayModalDiv(flag, id) {
	var modal_div = document.getElementById(id);

	if(flag) {
		var pageDimensions = getPageDimensions();

		modal_div.style.height = pageDimensions[1];
		modal_div.style.width = pageDimensions[0];

		modal_div.style.visibility='';
		modal_div.style.display='';
	} else {
		modal_div.style.visibility='hidden';
		modal_div.style.display='none';

		modal_div.style.height = "0px";
		modal_div.style.width = "0px";
	}

	return modal_div;
}

function hideModalDiv(id){
	displayModalDiv(false, id);
	if(is_ie6){
			var iframe = document.getElementById(id + "-iframe");
			iframe.style.display = "none";
	}
}

function showModalDiv(id){
	var modal_div = displayModalDiv(true, id);
	if(is_ie6) {
			var iframe = document.getElementById(id + "-iframe");
			iframe.style.height = modal_div.style.height;
			iframe.width = modal_div.style.width;
			iframe.style.display = "";
	}
}

