//var DEBUG = 0;
// Core UWT Methods

function centerElement (element, parentEl) {
    var w, h, pw, ph;
    var d = Element.getDimensions(element);
    w = d.width;
    h = d.height;
    Position.prepare();
    if (!parentEl) {
        var ws = document.viewport.getDimensions();
        pw = ws.width;
        ph = ws.height;
    } else {
        pw = parentEl.getWidth;
        ph = parentEl.getHeight;
    }
    element.style.top  = ((ph/2) - (h/2)) + "px";
    element.style.left = ((pw/2) - (w/2)) + "px";
}

function redirect (url) {
    window.location = url;
}

function redirectToHash (e) {
    Event.stop(e);
    var url = this.href;
    window.location = url;
}

function closeInPageDiv(e) {
    var els = this.ancestors();
    if ( els[0] ) {
        els[0].hide();
    }
    Event.stop(e);
}
    
function closeDiv(e) {
    this.getOffsetParent().hide();
    if ( $('primary_modal_content') ) {
        $('primary_modal_content').innerHTML = '';
    }
    showFlash();
    Event.stop(e);
    setOverlay(0);
}

function closeModals() {
    if ( $('primary_modal_content') ) {
        $('primary_modal').style.display = 'none';
        showFlash();
        setOverlay(0);
    }
}
    
function openURLFullScreen(e) {
    Event.stop(e);
    var url = _getHashParam(this.href);
    var max_width = screen.width + "px";
    var max_height = screen.height + "px";
    url += "&width=" + ( screen.width - 40 ) +
        "&height=" + ( Math.round(screen.width * 1.2) ); 
    var options = "width=" + max_width + ",height=" + max_height +
        ",toolbar=no,location=no,menubar=no,status=no,resizable=yes" +
        ",scrollbars=yes,top=0,left=0,alwaysRaised=1,titlebar=no"; 
    window.open(url,"UWT",options);
}

function _getHashParam(href) {
    var reg = new RegExp("#(.+)$");
    var result = reg.exec(href);
    return ( result ) ? result[1] : null;
}

function _getLastParam() {
    var reg = new RegExp("/([^/]+)$");
    var result = reg.exec(location.pathname);
    return ( result ) ? result[1] : null;
}

function reloadPage() {
    redirect(parent.location.pathname);
}

function filterSongbookType(e) {
    Event.stop(e);
    var typeId = this.value || 0;
    var songbookBrowseURL = "/Guitar-Songbooks/" + typeId;;
    redirect(songbookBrowseURL);
}

function filterSearchResults(e) {
    Event.stop(e);
    var params = $('search_filter_form').serialize(true);
    _makeAJAXRequestStd(this,'/item/ajax_filter_search',params,'get');
}
    
function updateErrorMessage(error,notice) {
    if ( $('in_page_response') ) {
        if ( ! notice ) { notice = '' };
        if ( ! error  ) { error  = '' };
        $('in_page_response_notice').innerHTML = notice;
        $('in_page_response_notice').style.display = 'block';
        $('in_page_response_error').innerHTML = error;
        $('in_page_response_error').style.display = 'block';
    }
    else if ( notice || error )  {
        showMessage(error,notice);
    }
}
    
function showMessage(error,notice) {
    var respDiv = $('response_message');
    var noticeDiv  = $('response_notice');
    var errorDiv   = $('response_error');

    if ( error )  { errorDiv.innerHTML = error; }
    if ( notice ) { noticeDiv.innerHTML = notice; }
    
    respDiv.style.display = 'block';
}

function showModalMessage(error,notice) {
    var noticeDiv  = $('modal_response_notice');
    var errorDiv   = $('modal_response_error');

    if ( error )  { errorDiv.innerHTML = error; }
    if ( notice ) { noticeDiv.innerHTML = notice; }
    if ( error || notice ) { $('modal_response').style.display = 'block'; }
}
    
function showProgressBar(show, text) {
    if ( text ) { $('page_loading_message').innerHTML = text; }
    if ( $('in_content_loading_div') ) {
        showProgressBarInContent(show);
    }
    else {
        showProgressBarStandard(show);
    }
}

function showProgressBarStandard(show) {
    var loadNode = $('loading_div');
    if ( !show ) {
        loadNode.style.display = 'none';
        $('primary_modal_content').style.display = 'block';
        $('primary_modal').style.display = 'none';
        return 1;
    }

    $('primary_modal_content').style.display = 'none';
    loadNode.style.display = 'block';
    $('primary_modal').style.display = 'block';
    centerElement($('primary_modal'));
    return 1;
}

function showProgressBarInContent(show) {
    var loadNode = $('in_content_loading_div');
    if ( !show ) {
        loadNode.style.display = 'none';
        $('modal_body').style.display = 'block';
        return 1;
    }
    $('modal_body').style.display = 'none';
    loadNode.style.display = 'block';
    centerElement($('primary_modal'));
    return 1;
}

function setOverlay(show) {
    if ( show ) {
        $('frame').addClassName('overlay');
    }
    else {
        $('frame').removeClassName('overlay');
    }
}
    
function showModal(show) {
    setOverlay(show);
    var primaryModal = $('primary_modal');
    if ( !show ) {
        primaryModal.style.display = 'none';
        return 1;
    }
    primaryModal.style.display = 'block';
    centerElement(primaryModal);
    return 1;
}

function trackEvent(category, action, label, value) {
    if ( _gaq ) {
        _gaq.push(['_trackEvent',category,action,label,value]);
    }
    else {
    }
}

function trackPageview(page) {
    if ( _gaq ) {
        _gaq.push(['_trackPageview',page])
    }
    else {
    }
}

function setGAScorchStatus(value) {
    if ( _gaq ) {
        _gaq.push(['_setCustomVar',1,'Scorch Status',value,1]);
    }
}
    
function internalError(transport) {
    showProgressBar(0);
    var message = ( transport.responseText ) ?
        "Sorry, there was an error: " + transport.responseText : transport;
    showMessage( message );
}

function showDiv(divID) {
    var div = $(divID);
    if ( !div ) {
        internalError(divID + " does not exist");
    }
    div.style.display = 'block';
}

function isOS64bit() {
    var regSafari = new RegExp("Safari");
    if ( regSafari.exec(navigator.userAgent) ) {
        var regSnowLeopard = new RegExp("Mac OS X 10_6");
        if ( regSnowLeopard.exec(navigator.userAgent) ) {
    	    return 1;
        }
    }
    return 0;
}
    
function isScorchInstalled() {
    if (navigator.plugins && navigator.plugins.length > 0) {
	var length = navigator.plugins.length;
	for (counter=0; counter < length; counter++ ) {
            var regScorch = new RegExp("Scorch");
            if ( regScorch.exec(navigator.plugins[counter].name) ) {
                setGAScorchStatus('installed');
                return 1;
            }
        }
        setGAScorchStatus('not installed');
        return 0;
    }
    else {
        if (window.ActiveXObject) {  
            var control = null;  
            try {  
                control = new ActiveXObject("ScorchActiveXPlugin.ScorchPlugin.1");  
            } catch (e) {
                setGAScorchStatus('not installed');
                return 0;  
            }  
            if (control) {
                setGAScorchStatus('installed');
                return 1;
                //version = control.GetVariable('$version').substring(4);  
            }  
        }
    }
    setGAScorchStatus('unknown');
    return 1; //let scorch default if it drops out for some reason.
}

function getSiblingUL(el) {
    var elArr = el.parentNode.select('ul');
    return elArr[0];
}

function setListScrollIndicators(el) {
    var liArr = getSiblingListArray(el);
    var lastIndex = _getHashParam(el.href) - 1;
    var divContainer = liArr[0].up().up();
    var showMoreAnchor = divContainer.select('.show_more_div')[0];
    var showLessAnchor = divContainer.select('.show_less_div')[0];
    if ( liArr[0].previous('li') ) {
        showLessAnchor.addClassName('more');
    }
    else {
        showLessAnchor.removeClassName('more');
    }
    if ( liArr[lastIndex].next('li') ) {
        showMoreAnchor.addClassName('more');
    }
    else {
        showMoreAnchor.removeClassName('more');
    }
}
    
function showLessList(e) {
    Event.stop(e);
    var lastIndex = _getHashParam(this.href) - 1;
    var liArr = getSiblingListArray(this);
    if ( toggleListElDisplay( liArr[0].previous('li') ) ) {
        toggleListElDisplay( liArr[lastIndex] );
    }
    setListScrollIndicators(this);
}

function showMoreList(e) {
    Event.stop(e);
    var lastIndex = _getHashParam(this.href) - 1;
    var liArr = getSiblingListArray(this);
    if ( toggleListElDisplay( liArr[lastIndex].next('li') ) ) {
        toggleListElDisplay( liArr[0] );
    }
    setListScrollIndicators(this);
}

function loadSWFs_dep() {
    if ( $('noteflight_player') ) {
        inlineLoadNoteflight();
    }
    if ( $('video_content') ) {
        inlineLoadBlip();
    }
    if ( $('video_player') ) {
        inlineLoadBlip();
    }
}
    
function loadSongbookPreview(e) {
    Event.stop(e);
    // Highlight the new one in the strip
    var containerUl = this.up('ul');
    var newLi = this.up('li');
    var oldUlArr = containerUl.select('.current_songbook_song');
    if ( oldUlArr[0] ) {
        oldUlArr[0].removeClassName('current_songbook_song');
        oldUlArr[0].down('.tab_with_art').removeClassName('current_songbook_song');
    }
    newLi.addClassName('current_songbook_song');
    newLi.down('.tab_with_art').addClassName('current_songbook_song');
    // Load the new songbook
    var itemID = _getHashParam(this.href);
    var params = {};
    params.item_id = itemID;
    params.songbook_id = $('songbook_id').value; 
    _makeAJAXRequestStd(this,'/item/songbook/reload_song_ajax',params,'get');
}
    
function getSiblingListArray(el) {
    var ulEl = getSiblingUL(el.parentNode);
    var liArr = ulEl.select('li.show');
    return liArr;
}

function removeMin(e) {
    this.removeClassName('min');
    this.removeClassName('min_action');
    this.siblings().each(function(el) {
        el.removeClassName('min');
    });
}
    
function toggleListElDisplay(el) {
    if ( ! el ) { return; }
    if ( el.hasClassName('show') ) {
        el.removeClassName('show');
        el.addClassName('hide');
        return "hide";
    }
    else {
        el.removeClassName('hide');
        el.addClassName('show');
        return "show";
    }
}

function toggleSongbookTable(e) {
    Event.stop(e);
    var songbookID = _getHashParam(this);
    var songbookClass = '.songbook_item_' + songbookID;
    var currentState;
    $$(songbookClass).each(function(el) {
        currentState = toggleListElDisplay(el);
    });
    this.innerHTML = ( currentState == "show" ) ? "[-] Songbook" : "[+] Songbook";   
}
    
function wrapTextWithHTML(e) {
    Event.stop(e);
    var div = this.parentNode;
    var reg = new RegExp("^(.+)_wrap_div$");
    var result = reg.exec(div.id);
    if ( ! result ) {
        return;
    }
    targetEl = $(result[1]);
    if ( ! targetEl ) {
        return;
    }
    var template = $('wrap_template').value;
    var argId = 1;
    while ( el = $(targetEl.id+ "_arg_" + argId) ) { 
        template = template.replace("<arg" + argId + ">",el.value);
        argId++;
    }
    var newText = targetEl.innerHTML + "\n" + template;
    targetEl.value = newText;
}
    
function toggleDiv(e) {
    Event.stop(e);
    var curDiv = this.up('div');
    var regOpened = new RegExp("^(.+)_opened$");
    var regClosed = new RegExp("^(.+)_closed$");
    var result = regOpened.exec(curDiv.id);
    var newDiv;
    if ( result ) {
        newDiv = $(result[1] + '_closed');
    }
    else {
        result = regClosed.exec(curDiv.id);
        if ( !result ) { return; }
        newDiv = $(result[1] + '_opened');
    }
    if ( ! newDiv ) {
        internalError("Failed to find other div.");
    }
    curDiv.style.display = 'none';
    newDiv.style.display = 'block';
}

function showMoreDiv(e) {
    Event.stop(e);
    var showMoreDiv = this.next('.show_more_div');
    if ( showMoreDiv.style.display == 'block' ) {
        showMoreDiv.style.display = 'none';
        this.innerHTML = '[+]';
    }
    else {
        showMoreDiv.style.display = 'block';
        this.innerHTML = '[-]';
    }
}
    
function _updateElement(elementId, html) {
    var element = $(elementId);
    if ( !element ) {
        if ( DEBUG ) {
            internalError("Failed to update element: " + elementId);
        }
        return;
    }
    element.innerHTML = html;
    element.style.display = '';
    
    setObserveElements(1);
}

function toggleSongbookDetails(e) {
    Event.stop(e);
    var el = this.up(0).next('.songbook_module_details');
    if ( el && el.style.display == 'block' ) {
        el.style.display = 'none';
        desetActive(this);
    }
    else if ( el ) {
        el.style.display = 'block';
        setActive(null,this);
    }
}

function showPreviewVideo () {
    var videoContentDiv = $('video_content');
    var topContainerDiv = $('top_container_v2');
    var showVideoAction = $('show_video_action');
    if ( ! videoContentDiv || ! topContainerDiv ) return 0;
    var primarySongTitle = $('primary_song_title').value;
    if ( videoContentDiv.style.display == 'block' ) {
        videoContentDiv.style.display = 'none';
        topContainerDiv.removeClassName('with_video');
        showVideoAction.removeClassName('with_min_video');
        $('show_video_action').style.display = 'block';
        $('hide_video_action').style.display = 'none';
        trackEvent('Video','Minimize',primarySongTitle);
    }
    else {
        videoContentDiv.style.display = 'block';
        topContainerDiv.addClassName('with_video');
        $('show_video_action').style.display = 'none';
        $('hide_video_action').style.display = 'block';
        trackEvent('Video','Enlarge',primarySongTitle);
    }
}

function loadBlip(videoFile,width,height,cssID) {
    var stampStr = "?t=" + new Date().getTime(); 
    var blipSWF = "https://blip.tv/scripts/flash/stratos.swf" + stampStr;
    var expressSWF = "/lib/js/swfobject/expressInstall.swf";
    var attributes = {
    };
    var flashvars = {
        file: videoFile + stampStr,
        allowsriptaccess: "true",
        enablejs: "true",
        allowfullscreen: "true",
        enablejs: "true",
        javascriptid: cssID,
        lightcolor: "0xFFFFFF",
        backcolor: "0x000000",
        autostart: "false",
        showinfo: "false",
        brandname: "UWT",
        brandlink: "http://uwt454.blip.tv/"
    };
    var params = {
        allowfullscreen: "true",
        allowScriptAccess: "always"
    };
    swfobject.embedSWF(blipSWF, cssID, width, height, "9.0.124", expressSWF, flashvars, params, attributes);
}

function loadYoutube(videoSrc,width,height,cssID) {
    var stampStr = "?t=" + new Date().getTime(); 
    // var chromeless = "http://www.youtube.com/apiplayer?enablejsapi=1&version=3&playerapiid=" + cssID + "&video_id=" + videoID;
    var expressSWF = "/lib/js/swfobject/expressInstall.swf";
    var attributes = {
        id: cssID,
    };
    var params = {
        allowScriptAccess: "always",
        allowfullscreen: "true"
    };
    swfobject.embedSWF(videoSrc, cssID, width, height, "8", null, null, params, attributes);
}
    
function loadNoteflight(width,playerMode,noteflightSWF,scoreURL) {
    var expressSWF = "/lib/js/swfobject/expressInstall.swf";
    var attributes = {
    };
    var flashvars = {
        playerMode: playerMode,
        score: scoreURL
    };
    var params = {
        type: "application/x-shockwave-flash",
        width: width,
        height: "100%",
        wmode: "opaque",
        allowfullscreen: "true",
        allowScriptAccess: "always"
    };

    swfobject.embedSWF(noteflightSWF, 'noteflight_player', width, "100%", "9.0.0", expressSWF, flashvars, params, attributes);
}
    
function closeElement(element) {
    var newEl = element;
    if ( typeof element.constructor == String ) { newEl = $(element); }
    newEl.hide();
}

function clearDefaultText (e) {
    this.value = '';
    this.style.color = 'black';
    this.focus();
    Event.stopObserving(this, 'focus', clearDefaultText);
}

function setModalKeyEvents (div) {
    Event.observe(div,'keydown',observeModalKeys);
    div.select('textarea').each(function(el) {
        Event.observe(el,'keydown',stopObservingEnter);
    });
}

function setModalFocus() {
    $$('.first_focus').each(function(el) {
        el.focus();
    });
}

function hideFlash() {
    /* hide all flash in the page */
    var flash = $$('embed');
    flash.each(function(el) {
        el.style.visibility = 'hidden';
    });
    var iframe = $$('iframe');
    iframe.each(function(el) {
        el.style.visibility = 'hidden';
    });
    var object = $$('object');
    object.each(function(el) {
        el.style.visibility = 'hidden';
    });
}
function showFlash() {
    /* show all flash */
    var flash = $$('embed');
    flash.each(function(el) {
        el.style.visibility = 'visible';
    });
    var iframe = $$('iframe');
    iframe.each(function(el) {
        el.style.visibility = 'visible';
    });
    var object = $$('object');
    object.each(function(el) {
        el.style.visibility = 'visible';
    });
}

function showWikiInfo(wiki_text) {
    $('wiki_information').innerHTML = wiki_text;
    $('wiki_information').style.display = 'block';
    setObserveElements(1);
    hideFlash();
}
    
function _initModal (html) {
    setOverlay(1);
    var primaryModalDiv = $('primary_modal');
    var primaryModalContent = $('primary_modal_content');
    if ( !primaryModalDiv || !primaryModalContent ) {
        internalError("Couldn't instantiate modal window objects: " +
                      "div: "      + primaryModalDiv +
                      " content: " + primaryModalContent
                     );
        return;
    }
    primaryModalContent.innerHTML = html;
    primaryModalContent.style.display = 'block';
    centerElement(primaryModalDiv);
    primaryModalDiv.style.display = 'block';
    setObserveElements(1);
    setModalKeyEvents(primaryModalDiv);
    setModalFocus();
    hideFlash();
}

function _handleModalError (response) {
    if ( $('modal_response_error') && response.error ) {
        _updateElement('modal_response_error',response.error);
        var primaryModalDiv = $('primary_modal');
        primaryModalDiv.style.display = 'block';
    }
    else if ( $('modal_response_notice') && response.notice ) {
        _updateElement('modal_response_notice',response.notice);
        var primaryModalDiv = $('primary_modal');
        primaryModalDiv.style.display = 'block';
    }
    else if ( response.error ) {
        showMessage(response.error);
    }
    
}
    
function _updateAJAX (json,modalResponse) {
    var h = $H(json.templates);

    h.each(function(pair) {
        switch(pair.key) {
        case 'primary_modal_content':
            _initModal(pair.value);
            break;
        case 'wiki_information':
            showWikiInfo(pair.value);
            break;
        default:
            _updateElement(pair.key, pair.value);
        }
    });

    if ( json.js_execute ) {
        eval(json.js_execute);
    }
    
    if ( json.response && json.response.js_execute ) {
        window[json.response.js_execute]();
    }
    
    if ( json.redirect_url ) {
        redirect(json.redirect_url);
    }

    if ( modalResponse && ( json.response && ( json.response.error || json.response.notice ) ) ) {
        _handleModalError(json.response);
    }
    else if ( json.response )  {
        updateErrorMessage(json.response.error,json.response.notice);
    }
    else {
        updateErrorMessage('','');
    }
}

function _validateForm (formId, responseId) {
    var valid = new Validation(formId, {onSubmit:false});
    var result = valid.validate();
    if ( ! result ) {
        responseId = responseId || 'modal_response_error';
        _updateElement(responseId,'Uh oh. Looks like there was an error.<br/>Check below...');
        $('modal_response').style.display = 'block';
        return 0;
    }
    return 1;
}

function setActive(e,el) {
    if ( !el ) {
        el = this;
    }
    el.addClassName('active');
}

function desetActive(that) {
    that.removeClassName('active');
}
    
function _insertViaAJAX (container, action, params, codeRef) {
    new Ajax.Updater(container, action, {
        parameters: params,
        insertion: 'bottom',
        onComplete: function (transport) {
            if ( codeRef ) { codeRef(); }
        },
        onFailure: function(transport) {
            internalError("Failed to insert into: " + container);
        }
    });
}
    
function _makeAJAXRequestStd (actionEl, action, params, method, codeRef) {
    if ( ! params.suppressProgressBar ) showProgressBar(1);
    new Ajax.Request(action,{
        method: method,
        parameters: params,
        onSuccess: function (transport) {
            showProgressBar(0);
            var response = transport.responseText.evalJSON();
            _updateAJAX(response,0);
            showModal(0);
            if ( codeRef ) {
                codeRef();
            }
            if ( actionEl ) {
                desetActive(actionEl);
            }
        },
        onFailure: function(transport) {
            internalError(transport);
        }
    });
}

function setJSEnabled() {
    _executeAJAX('/set_session',{},'POST');
}
    
function _executeAJAX (action, params, method) {
    new Ajax.Request(action,{
        method: method,
        parameters: params,
        onSuccess: function (transport) {
        },
        onFailure: function(transport) {
        }
    });
}

function _getJSONRequest (action, params, method, codeRef) {
    showProgressBar(1);
    new Ajax.Request(action,{
        method: method,
        parameters: params,
        onSuccess: function (transport) {
            var json = transport.responseText.evalJSON();
            if ( json.response.error ) {
                showMessage(json.response.error,json.response.notice);
            }
            else {
                if ( json.response.notice ) {
                    showMessage('',json.response.notice);
                }
                if ( codeRef ) { codeRef(json); }
            }
            showProgressBar(0);
        },
        onFailure: function(transport) {
            showProgressBar(0);
            internalError("Sorry, there was an unknown error.");
        }
    });
}

function _makeAJAXRequestModal (url, params, method, codeRef) {
    showProgressBar(1);
    new Ajax.Request(url,{
        method: method,
        parameters: params,
        onSuccess: function (transport) {
            showProgressBar(0);
            var response = transport.responseText.evalJSON();
            _updateAJAX(response,1);
            if ( codeRef ) { codeRef(); }
            trackPageview(url);
        },
        onFailure: function(transport) {
            internalError(transport);
        }
    });
}

function _initiateAJAXModal (url,params,codeRef) {
    showProgressBar(1);
    if ( ! params ) {
        params = {};
    }
    new Ajax.Request(url, {
        parameters: params,
        method: "get",
        onSuccess: function (transport) {
            showProgressBar(0);
            var json = transport.responseText.evalJSON();
            _initModal(json.templates.primary_modal_content);
            if ( codeRef ) { codeRef(); }
            trackPageview(url);
        },
        onFailure: function(transport) {
            internalError(transport);
        }
    });
}

// AJAX methods

// Login Register methods
    
function initiateLoginModal (e) {
    Event.stop(e);
    _initiateAJAXModal('/login/init_login_modal');
}

function initiateRegisterModal (e) {
    Event.stop(e);
    var hashVal = _getHashParam(this);
    if ( hashVal == 'ft' ) {
        trackPageview('/links/free_tabs');
    }
    _initiateAJAXModal('/login/init_registration_modal');
}

function initiateForgetPasswordModal (e) {
    Event.stop(e);
    _initiateAJAXModal('/login/init_forget_password_modal');
}

function initiateLoginSecureModal (e) {
    Event.stop(e);
    _initiateAJAXModal('/login/init_login_secure_modal');
}

function initiateRegisterSecureModal (e) {
    Event.stop(e);
    _initiateAJAXModal('/login/init_registration_secure_modal');
}

function initiateForgetPassworSecuredModal (e) {
    Event.stop(e);
    _initiateAJAXModal('/login/init_forget_password_secure_modal');
}
    
function initiatePurchaseModal (e) {
    Event.stop(e);
    var params = {};
    if ( this.hasClassName('songbook_purchase') ) {
        params.songbook_id = $('songbook_id').value;
    }
    else {
        var hashID = _getHashParam(this);
        if ( hashID ) {
            params.item_id = hashID;
        }
        else {
            params.item_id = $('item_id').value; 
        }
    }
    _initiateAJAXModal('/purchase/init_purchase_modal',params);
}

function initiateChangePaymentModal (e) {
    Event.stop(e);
    _initiateAJAXModal('/purchase/init_change_payment_modal');
}

function initiateApplyDiscountModal (e) {
    Event.stop(e);
    _initiateAJAXModal('/purchase/init_apply_discount_modal');
}

function initiatePaypalConfirmModal () {
    _initiateAJAXModal('/purchase/paypal_confirm');
}

function initiateAffiliateSignupModal (e) {
    Event.stop(e);
    _initiateAJAXModal('/affiliate/init_signup_modal');
}

function previewDiscount (e) {
    Event.stop(e);
    var params = {};
    //params.discount_code = $('discount_code').value;
    //params.pin           = $('pin').value;
    _makeAJAXRequestModal('/purchase/init_purchase_modal',params,'post');
}

function applyDiscount (e) {
    Event.stop(e);
    var params = {};
    params.discount_code = $('discount_code').value;
    params.pin           = $('pin').value;

    if ( !params.discount_code ) {
        showModalMessage('You must enter a Discount Code or Gift Card to apply one to your account.');
        return;
    }

    _makeAJAXRequestModal('/api/rest/user_accounts/update/discount',params,'post');
}
    
function logout (e) {
    Event.stop(e);
    var params = {};
    _makeAJAXRequestModal('/user/logout',params,'post');
}

function logoutLogin (e) {
    Event.stop(e);
    var params = {};
    _makeAJAXRequestModal('/user/logout_login_secure',params,'post');
}

function clearPurchaseSession (e) {
    Event.stop(e);
    var params = {};
    _executeAJAX('/purchase/clear_purchase_session',params,'post');
}
    
function _authenticateUser (e) {
    if ( ! _validateForm('login_form') ) { return; }
    var params = $('login_form').serialize(true);
    _makeAJAXRequestModal('/user/authenticate',params,'post');
    return false;
}

function _registerUser (e) {
    if ( ! _validateForm('registration_form') ) { return; }
        
    var params = $('registration_form').serialize(true);
    params.pp_purchase = ( $('pp_purchase') ) ? 1 : 0;
    
    _makeAJAXRequestModal('/api/rest/user/create/user',params,'post');
}

function _applyNewCustomerCode (e) {
    var params = {};
    params.email         = $('email').value;
    params.password      = $('password').value;
    params.confirm       = $('confirm').value;
    params.name_first    = $('name_first').value;
    params.name_last     = $('name_last').value;
    params.discount_code = $('discount_code').value;
    params.pin           = $('pin').value;
    
    _makeAJAXRequestModal('/api/rest/user/create/user',params,'post');
}
    
function authenticateUser (e) {
    Event.stop(e);
    _authenticateUser(e);
}

function registerUser (e) {
    Event.stop(e);
    _registerUser(e);
}

function applyNewCustomerCode (e) {
    Event.stop(e);
    _applyNewCustomerCode(e);
}

function resetPassword (e) {
    Event.stop(e);
    if ( ! _validateForm('forget_password_form') ) { return; }
    var params = $('forget_password_form').serialize();
    _makeAJAXRequestModal('/user/reset_password',params,'post');
}
    
function getWikiInfo(e) {
    Event.stop(e);
    var params = {};
    //$('wiki_information').style.display = 'block';
    setObserveElements(1);
    hideFlash();
    _makeAJAXRequestModal('/songs/get_wiki', params, 'get');
}

// Store related JS

function setCurrentChartSwap (e) {
    Event.stop(e);
    var linkRegex = new RegExp("^chart_swap_link_(.+)$");
    var result = linkRegex.exec(this.id);

    $$('.set_current_chart_swap.current_link').each(function(el) {
        el.removeClassName('current_link');
    });
    this.addClassName('current_link');
    
    var newUl = $('chart_swap_' + result[1]);
    if ( !newUl ) {
        internalError('Failed to find new chart_swap section');
        return;
    }

    $$('.chart_swap_uls.current').each(function(el) {
        el.addClassName('hidden');
        el.removeClassName('current');
    });
    newUl.removeClassName('hidden');
    newUl.addClassName('current');
}

// Purchase related methods

function reserveTab (e) {
    Event.stop(e);
    var params = $('tablature_action_form').serialize(true);
    _makeAJAXRequestModal('/api/rest/users_items/create/reserve',params,'post');
}

function signupAffiliate (e) {
    Event.stop(e);
    if ( ! _validateForm('affiliate_signup_form') ) { return; }
    var params = $('affiliate_signup_form').serialize(true);
    _makeAJAXRequestModal('/api/rest/affiliate/create',params,'post');
}

function initExpressCheckout (e) {
    Event.stop(e);
    var params = {};
    _makeAJAXRequestModal('/purchase/init_express_checkout',params,'post');
}
    
function submitPaymentInfo (e) {
    Event.stop(e);
    if ( ! _validateForm('get_payment_form') ) {
        return;
    }
    var params = $('get_payment_form').serialize();
    _makeAJAXRequestModal('/api/rest/user_accounts/create/account',params,'post');
}
    
function submitRegisterStep(e) {
    Event.stop(e);
    if ( ! _validateForm('new_user_form') ) {
        return;
    }
    var params = $('new_user_form').serialize();
    _makeAJAXRequestModal('/api/rest/user/create/user',params,'post');
}

function submitDeliveryInfo(e) {
    Event.stop(e);
    if ( ! _validateForm('delivery_info_form') ) {
        return;
    }
    var params = $('delivery_info_form').serialize();
    _makeAJAXRequestModal('/api/rest/delivery_info/add',params,'post');
}

function submitAccountUpdate(e) {
    Event.stop(e);
    // Validate each of the three forms.
    if ( ! _validateForm('my_account_form','in_page_response_error') ) {
        return;
    }

    // serialize each form that exists (only registration is guaranteed)
    var params = $('my_account_form').serialize();

    // make the ajax request
    _makeAJAXRequestStd(this,'/api/rest/user/update/account',params,'post');
}
    
function confirmPurchase(e) {
    Event.stop(e);
    if ( $('discount_code') && $('discount_code').value ) {
        showModalMessage('Please Apply the Discount Code before purchasing.');
        return;
    }

    Event.stopObserving(this, 'click', confirmPurchase);
    var params = {};
    _makeAJAXRequestModal('/api/rest/users_items/create/purchase',params,'post');
}

function cancelPurchase(e) {
    Event.stop(e);
    var params = {};
    _makeAJAXRequestModal('/api/rest/users_items/create/cancel',params,'post');
}

function confirmExpressPurchase(e) {
    Event.stop(e);
    var params = {};
    _makeAJAXRequestModal('/api/rest/users_items/create/purchase_express',params,'post');
}

function makeComment(e) {
    Event.stop(e);
    if ( ! _validateForm('add_comment_form') )
        return;
    var params = $('add_comment_form').serialize();
    params += '&' + $('comments_filter_form').serialize();
    _makeAJAXRequestModal('/api/rest/comments/create/user',params,'post');
}

function loadCommentsList (e) {
    Event.stop(e);
    var params = $('comments_filter_form').serialize(true);
    _makeAJAXRequestModal('/api/rest/comments/list',params,'get');
}
    
function reloadMusicRainScore(e) {
    Event.stop(e);
    var params = {};
    _getJSONRequest('/api/rest/users_items/update/user_reprint',params,'post',handleReprintResponse);
}

function requestAdditionalPrint(user_id, item_id) {
    var params = {};
    params.user_id = user_id;
    params.item_id = item_id;
    _getJSONRequest('/api/rest/users_items/update/admin_reprint',params,'post');
}
    
function handleReprintResponse(json) {
    if ( json.response.success ) {
        reloadPage();
    }
    else {
        internalError("Sorry, we were unable to reload the page.");
    }
}

function coverPrintButton() {
    var coverEl = $('music_rain_cover_print_button');
    coverEl.style.display = 'block';
}

/* Adding Extra validate Fucntions */

function addValidationFunctions() {
    
    Validation.add('validate-year',
                   'You must provide a 4-digit year like (2012)',
                   function( value ) {
                       var regex  = new RegExp("^[0-9]{4}$");
                       return regex.exec(value);
                   }
                  );

    Validation.add('validate-month',
                   'You must provide a 2-digit month 01-12.',
                   function( value ) {
                       var regex  = new RegExp("^(0[0-9]|1[0-2])$");
                       return regex.exec(value);
                   }
                  );
                  
    Validation.add('validate-comment-text',
                   'You need to write some kind of comment before submitting it.',
                   function( value ) {
                       var regex  = new RegExp("^make your comment here$");
                       return !regex.exec(value);
                   }
                  );

    Validation.add('validate-comment-rating',
                   'You need to rate this using the stars before submitting it.',
                   function( value ) {
                       return value;
                   }
                  );
}    

function $RF(el, radioGroup) {
    if($(el).type && $(el).type.toLowerCase() == 'radio') {
	var radioGroup = $(el).name;
	var el = $(el).form;
    } else if ($(el).tagName.toLowerCase() != 'form') {
	return false;
    }
	 
    var checked = $(el).getInputs('radio', radioGroup).find(
	function(re) {return re.checked;}
    );
    return (checked) ? $F(checked) : null;
}
                  
// Setup event handlers.
  
function observeModalKeys(e) {
    switch (e.keyCode)
    {
    case Event.KEY_RETURN:
        $$('.form_submit').each(function(link) {
            link.fire('div:return');
        });
        Event.stop(e);
        break;
    case Event.KEY_ESC:
        this.hide();
        break;
    }
}

function stopObservingEnter(e) {
    switch (e.keyCode)
    {
    case Event.KEY_RETURN:
        this.value = this.value + "\r";
        Event.stop(e);
    }
}

function setObserveElements() {
    $$('.login_link').each(function(link) {
        link.observe('click', initiateLoginModal);
    });
    $$('.register_link').each(function(link) {
        link.observe('click', initiateRegisterModal);
    });
    $$('.forget_password_link').each(function(link) {
        link.observe('click', initiateForgetPasswordModal);
    });
    $$('.login_secure_link').each(function(link) {
        link.observe('click', initiateLoginSecureModal);
    });
    $$('.register_secure_link').each(function(link) {
        link.observe('click', initiateRegisterSecureModal);
    });
    $$('.forget_password_secure_link').each(function(link) {
        link.observe('click', initiateForgetSecureModal);
    });
    $$('.affiliate_signup_link').each(function(link) {
        link.observe('click', initiateAffiliateSignupModal);
    });
    $$('.close_link').each(function(link) {
        link.observe('click', closeDiv);
    });
    $$('.close_in_page_link').each(function(link) {
        link.observe('click', closeInPageDiv);
    });
    $$('.logout_link').each(function(link) {
        link.observe('click', logout);
    });
    $$('.logout_login_link').each(function(link) {
        link.observe('click', logoutLogin);
    });
    $$('.toggle_div').each(function(link) {
        link.observe('click', toggleDiv);
    });
    $$('.show_more_action').each(function(link) {
        link.observe('click', showMoreDiv);
    });
    $$('.clear_default').each(function(input) {
        input.observe('focus', clearDefaultText);
    });
    $$('.reserve_action').each(function(link) {
        link.observe('click', reserveTab);
    });
    $$('.purchase_action').each(function(link) {
        link.observe('click', initiatePurchaseModal);
    });
    $$('.preview_discount_action').each(function(link) {
        link.observe('click', previewDiscount);
    });
    $$('.apply_discount_action').each(function(link) {
        link.observe('click', applyDiscount);
    });
    $$('.change_payment_info').each(function(link) {
        link.observe('click', initiateChangePaymentModal);
    });
    $$('.apply_discount_to_account').each(function(link) {
        link.observe('click', initiateApplyDiscountModal);
    });
    $$('.set_current_chart_swap').each(function(link) {
        link.observe('click', setCurrentChartSwap);
    });
    $$('.wiki_info').each(function(link) {
        link.observe('click', getWikiInfo);
    });
    $$('.wrap_text_with_html').each(function(link) {
        link.observe('click', wrapTextWithHTML);
    });
    $$('.open_url_full_screen').each(function(link) {
        link.observe('click', openURLFullScreen);
    });
    $$('.toggle_opened').each(function(div) {
        div.style.display = 'none';
    });
    $$('.toggle_closed').each(function(div) {
        div.style.display = 'block';
    });
    $$('.show_less').each(function(link) {
        link.observe('click', showLessList);
    });
    $$('.show_more').each(function(link) {
        link.observe('click', showMoreList);
    });
    $$('.load_songbook_preview').each(function(link) {
        link.observe('click', loadSongbookPreview);
    });
    $$('.toggle_songbook_table').each(function(link) {
        link.observe('click', toggleSongbookTable);
    });
    $$('.toggle_songbook_details').each(function(el) {
        el.observe('click',toggleSongbookDetails);
    });
    $$('.toggle_video').each(function(el) {
        Event.observe(el,'click',showPreviewVideo);
    });
    $$('.min_action').each(function(el) {
        Event.observe(el,'focus',removeMin);
    });
    $$('.comments_filter').each(function(el) {
        Event.observe(el,'change',loadCommentsList);
    });
    $$('.songbook_type_filter').each(function(el) {
        Event.observe(el,'change',filterSongbookType);
    });
    $$('.search_filter').each(function(el) {
        Event.observe(el,'change',filterSearchResults);
    });
    $$('.button').each(function(el) {
        Event.observe(el,'click',setActive);
    });
        
    var el;
    if ( el = $('background_click') ) {
        Event.observe(el,'click',redirectToHash);
    }
    if ( el = $('register_action') ) {
        Event.observe(el,'click',registerUser);
        Event.observe(el,'div:return',registerUser);
    }
    if ( el = $('apply_new_customer_code_action') ) {
        Event.observe(el,'click',applyNewCustomerCode);
        Event.observe(el,'div:return',applyNewCustomerCode);
    }
    if ( el = $('authenticate_action') ) {
        Event.observe(el,'click',authenticateUser);
        Event.observe(el,'div:return',authenticateUser);
    }
    if ( el = $('reset_password_action') ) {
        Event.observe(el,'click',resetPassword);
        Event.observe(el,'div:return',resetPassword);
    }
    if ( el = $('make_comment_action') ) {
        Event.observe(el,'click',makeComment);
        Event.observe(el,'div:return',makeComment);
    }
    if ( el = $('submit_payment_info_action') ) {
        Event.observe(el,'click',submitPaymentInfo);
        Event.observe(el,'div:return',submitPaymentInfo);
    }
    if ( el = $('submit_register_step') ) {
        Event.observe(el,'click',submitRegisterStep);
        Event.observe(el,'div:return',submitRegisterStep);
    }
    if ( el = $('submit_delivery_info_action') ) {
        Event.observe(el,'click',submitDeliveryInfo);
        Event.observe(el,'div:return',submitDeliveryInfo);
    }
    if ( el = $('confirm_purchase_action') ) {
        Event.observe(el,'click',confirmPurchase);
        Event.observe(el,'div:return',confirmPurchase);
    }
    if ( el = $('cancel_purchase_action') ) {
        Event.observe(el,'click',cancelPurchase);
        Event.observe(el,'div:return',cancelPurchase);
    }
    if ( el = $('confirm_express_purchase_action') ) {
        Event.observe(el,'click',confirmExpressPurchase);
        Event.observe(el,'div:return',confirmExpressPurchase);
    }
    if ( el = $('affiliate_signup_action') ) {
        Event.observe(el,'click',signupAffiliate);
        Event.observe(el,'div:return',signupAffiliate);
    }
    if ( el = $('init_express_checkout') ) {
        Event.observe(el,'click',initExpressCheckout);
    }
    if ( el = $('submit_account_update') ) {
        Event.observe(el,'click',submitAccountUpdate);
    }
    if ( $('no_scorch') && ! isScorchInstalled() ) {
        $('no_scorch').style.display = 'block';
        $('scorch_accented_div').style.display = 'none';
        $('tablature_player_v2').removeClassName('scorch');
        $('tablature_player_v2').addClassName('no_scorch');
        // Silly hack to make FF give us the diff space betw scorch/noscorch.
        if ( $('comments_div') ) {
            $('comments_div').style.margin = '0px';
            $('comments_div').style.margin = '10px 10px 10px 0px';
        }
        if ( $('song_trivia_div') ) {
            $('song_trivia_div').style.margin = '0px';
            $('song_trivia_div').style.margin = '10px 10px 10px 0px';
        }
        // end of silly hack.
        if ( $('tab_player_top_notes') ) {
            $('tab_player_top_notes').style.display = 'none';
        }
    }
    if ( $('os_is_64_bit') && isOS64bit() ) {
        $('os_is_64_bit').style.display = 'block';
        //$('ScorchPlug-in').style.display = 'none';
        //$('tab_player_top_notes').style.display = 'none';
    }
    if ( el = $('reload_music_rain_score') ) {
        Event.observe(el,'click',reloadMusicRainScore);
    }
    if ( el = $('music_rain_iframe') ) {
        coverPrintButton();
    }
    setJSEnabled();
}
     
Event.observe(window, 'load', function(e) {
    setObserveElements();
    addValidationFunctions();
    return 1;
});

    
    

    


