﻿var modulePK = getQuerystring('modulePK');
var postback = false;
var UrlPrefix = 'http://competitions.fwmedia.com/services/';
var galleryScriptSrc = UrlPrefix + 'js/FW.gallery.js';
var jqueryScriptSrc = UrlPrefix + 'js/jquery-1.3.2.js';
var jqueryLightboxSrc = UrlPrefix + 'js/jquery.lightbox-0.5.min.js';
var gallerifficHistorySrc = UrlPrefix + 'js/jquery.history.js';
var gallerifficOpacityRolloverSrc = UrlPrefix + 'js/jquery.opacityrollover.js';
var gallerifficCssHref = UrlPrefix + 'css/galleriffic.css';
var jqueryLightboxCssHref = UrlPrefix + 'css/jquery.lightbox-0.5.css';
var viewLargerIcon = UrlPrefix + 'images/view-larger-image.jpg';
//var modulesHandlerUrl = "ModulesHandler.ashx?action=getdata&callback=renderModule&modulePK=" + modulePK + "";
var modulesUrlPrefix = UrlPrefix + 'ModulesHandler.ashx?';
//var getCategoriesUrl = 'ModulesHandler.ashx?action=getcategories&callback=bindCategories&modulePK=' + modulePK;
//var modulesHandler = new ajaxObject('ModulesHandler.ashx', attachScript);

(function() {
    buildModule();
    createCssLink(gallerifficCssHref, function() {
        createCssLink(jqueryLightboxCssHref, function() {
            createScriptTag(jqueryScriptSrc, function() {
                createScriptTag(jqueryLightboxSrc, function() {
                    createScriptTag(galleryScriptSrc, function() {
                        createScriptTag(gallerifficHistorySrc, function() {
                            createScriptTag(gallerifficOpacityRolloverSrc, function() {
                                createScriptTag(modulesUrlPrefix + 'action=getcategories&callback=bindCategories&modulePK=' + modulePK);
                            });
                        });
                    });
                });
            });
        });  
    });
})();

function buildModule() {
    var compModule = document.createElement('div');
    compModule.id = 'compModule';
    var html = '<h1 id="compModule_CompetitionTitle"></h1>';
    html += '<div id="compModule_Categories">';
    html += '<strong>Select Category:</strong> &nbsp;';
    html += '<select id="compModule_CatList" name="compModule_CatList" OnChange="changeCategory(this[selectedIndex].value)">';
    html += '<option value="All" selected>All</option>';
    html += '</select>';
    html += '</div>';
    html += '<div id="compModule_Gallery">';
    html += '</div>';
    
    compModule.innerHTML = html;
    var loader = document.getElementById('compModule_Script');
    loader.parentNode.insertBefore(compModule, loader);
}

function bindCategories(jsonObject) {
    if (jsonObject != undefined && jsonObject.length > 0) {
        removeScriptTag();
        document.getElementById('compModule_Categories').style.display = 'block';
        var $categories = document.getElementById('compModule_CatList');
        
        for (var i = 0; i < jsonObject.length; i++) {
            var $option = document.createElement('option');
            $option.text = jsonObject[i].CategoryName;
            $option.value = jsonObject[i].CategoryName;;     
                   
            $categories.options.add($option);
        }
        
        var index = $categories.selectedIndex;
        var selectedValue = $categories[index].value;
        
        if (selectedValue === 'All') {
            createScriptTag(modulesUrlPrefix + 'action=getdata&callback=renderModule&modulePK=' + modulePK);
        } else {
            createScriptTag(modulesUrlPrefix + 'action=getdataforcategory&callback=renderModule&modulePK=' + modulePK + '&categoryID=' + selectedValue);
        }
    } else {
        createScriptTag(modulesUrlPrefix + 'action=getdata&callback=renderModule&modulePK=' + modulePK);
    }
}

function changeCategory(selectedValue) {
    postback = true;
    if (selectedValue === 'All') {
        createScriptTag(modulesUrlPrefix + 'action=getdata&callback=renderModule&modulePK=' + modulePK);
    } else {
        createScriptTag(modulesUrlPrefix + 'action=getdataforcategory&callback=renderModule&modulePK=' + modulePK + '&categoryID=' + selectedValue);
    }
}

function renderModule(jsonObject) {
    removeScriptTag();
    document.getElementById('compModule_CompetitionTitle').innerHTML = jsonObject.CompetitionTitle;
    var html = '<div id="compModule_Content">';
    html += '<div id="compModule_Controls" class="controls"></div>';
    html += '<div class="slideshow-container">';
    html += '<div id="compModule_Loading" class="loader"></div>';
    html += '<div id="compModule_Slideshow" class="slideshow"></div>';
    html += '<div style="clear: both;"></div>'; 
    html += '</div>'; // close slideshow container    
    html += '<div id="compModule_Caption" class="embox"></div>';    
    html += '</div>'; // close content
    html += '<div id="compModule_Navigation" class="navigation">';
    html += '<ul class="navItems noscript">';
    
    if (jsonObject.DisplayEntries.length < 1) {
        html += '<li>jsonObject.DisplayEntries returned no data.</li>';
    } else {
        if (jsonObject.DisplayType === 1) { // Image display module
            for (var i = 0; i < jsonObject.DisplayEntries.length; i++) {
			
				if (jsonObject.DisplayEntries[i].DisplayTitle == "") {
                    jsonObject.DisplayEntries[i].DisplayTitle = "Untitled Image";
                }
			
                if (jsonObject.DisplayEntries[i].DisplayKeys[0]) {
                    html += '<li class="image">';
                    html += '<a class="navItem image" type="image" href="http://competitions.fwmedia.com/images/' + jsonObject.DisplayEntries[i].DisplayKeys[0] + '.ashx?k=normal" title="' + jsonObject.DisplayEntries[i].DisplayTitle + '">';
                    html += "<span></span>";
                    html += '<img src="http://competitions.fwmedia.com/images/' + jsonObject.DisplayEntries[i].DisplayKeys[0] + '.ashx?k=normal" alt="' + jsonObject.DisplayEntries[i].DisplayTitle + '" />';
                    html += '</a>';                       
                    html += '<ul class="slideItems">';
                    for (var j = 0; j < jsonObject.DisplayEntries[i].DisplayKeys.length; j++) {
                        html += '<li class="image">';
                        html += '<a class="slideItem image" href="http://competitions.fwmedia.com/images/' + jsonObject.DisplayEntries[i].DisplayKeys[j] + '.ashx?k=normal" title="' + jsonObject.DisplayEntries[i].DisplayTitle + '">';
                        html += '<span></span>';
                        html += '<img src="http://competitions.fwmedia.com/images/' + jsonObject.DisplayEntries[i].DisplayKeys[j] + '.ashx?k=normal" alt="' + jsonObject.DisplayEntries[i].DisplayTitle + '" />';
                        html += '</a>';
                        html += '</li>';
                    }
                    //html += '<div style="clear: both;"></div>'; 
                    html += '</ul>';
                    html += '<div class="slideCaption">';                
                    html += '<div class="slideTitle">' + jsonObject.DisplayEntries[i].DisplayTitle + '</div>';
                    html += '<div class="slideDesc">';
                    for (var x = 0; x < jsonObject.DisplayEntries[i].DisplayFields.length; x++) {
                        html += '<strong>' + jsonObject.DisplayEntries[i].DisplayFields[x].FieldName + ':</strong>&nbsp;' + jsonObject.DisplayEntries[i].DisplayFields[x].FieldValue + '<br />';
                    }
                    html += '</div>';
                    html += '</div>';
                    html += '<a class="slideViewLarger" target="_blank" href="http://competitions.fwmedia.com/images/' + jsonObject.DisplayEntries[i].DisplayKeys[0] + '.ashx?k=normal"><img src="' + viewLargerIcon + '" alt="View Larger" /><strong>View Larger</strong></a>';
                    html += '<input type="hidden" name="moduleType" value="' + jsonObject.ModuleType + '"/>';
                    html += '<input type="hidden" name="entryID" value="' + jsonObject.DisplayEntries[i].EntryID + '"/>';
                    html += '<input type="hidden" name="moduleID" value="' + modulePK + '"/>';
                    html += '</li>';
                }
            }
        } else if (jsonObject.DisplayType === 2) { // Video display module
            for (var i = 0; i < jsonObject.DisplayEntries.length; i++) {
			
			if (jsonObject.DisplayEntries[i].DisplayTitle == "") {
                    jsonObject.DisplayEntries[i].DisplayTitle = "Untitled Video";
                }
			
                html += '<li>';
                html += '<a class="navItem" type="video" href="' + jsonObject.DisplayEntries[i].DisplayKeys[0] + '" title="' + jsonObject.DisplayEntries[i].DisplayTitle + '">' + jsonObject.DisplayEntries[i].DisplayTitle + '</a>';
                html += '<ul class="slideItems">';
                var count = 1;
                for (var j = 0; j < jsonObject.DisplayEntries[i].DisplayKeys.length; j++) {
                    html += '<li>';
                    html += '<a class="slideItem" href="' + jsonObject.DisplayEntries[i].DisplayKeys[j] + '" title="' + jsonObject.DisplayEntries[i].DisplayKeys[j] + '">';
                    html += 'Video ' + count;
                    html += '</a>';
                    html += '</li>';
                    count++;
                }
                html += '<div style="clear: both;"></div>'; 
                html += '</ul>';
                html += '<div class="slideCaption">';
                html += '<div class="slideTitle">' + jsonObject.DisplayEntries[i].DisplayTitle + '</div>';
                html += '<div class="slideDesc">';
                for (var x = 0; x < jsonObject.DisplayEntries[i].DisplayFields.length; x++) {
                    html += '<strong>' + jsonObject.DisplayEntries[i].DisplayFields[x].FieldName + ':</strong>&nbsp;' + jsonObject.DisplayEntries[i].DisplayFields[x].FieldValue + '<br />';
                }
                html += '</div>';
                html += '</div>';
                html += '<input type="hidden" name="moduleType" value="' + jsonObject.ModuleType + '"/>';
                html += '<input type="hidden" name="entryID" value="' + jsonObject.DisplayEntries[i].EntryID + '"/>';
                html += '<input type="hidden" name="moduleID" value="' + modulePK + '"/>';
                html += '</li>';
            }
        } else if (jsonObject.DisplayType === 3) { // Text display module
            for (var i = 0; i < jsonObject.DisplayEntries.length; i++) {
			
				if (jsonObject.DisplayEntries[i].DisplayTitle == "") {
                    jsonObject.DisplayEntries[i].DisplayTitle = "Untitled Text";
                }
			
                html += '<li>';
                html += '<a class="navItem" type="text" href="' + jsonObject.DisplayEntries[i].DisplayKeys[0] + '" title="' + jsonObject.DisplayEntries[i].DisplayTitle + '">' + jsonObject.DisplayEntries[i].DisplayTitle + '</a>';
                html += '<ul class="slideItems">';
                var count = 1;
                for (var j = 0; j < jsonObject.DisplayEntries[i].DisplayKeys.length; j++) {
                    html += '<li>';
                    html += '<a class="slideItem" href="' + jsonObject.DisplayEntries[i].DisplayKeys[j] + '" title="' + jsonObject.DisplayEntries[i].DisplayKeys[j] + '">';
                    html += 'Item ' + count;
                    html += '</a>';
                    html += '</li>';
                    count++;
                }
                html += '<div style="clear: both;"></div>';
                html += '</ul>';
                html += '<div class="slideCaption">';
                html += '<div class="slideTitle">' + jsonObject.DisplayEntries[i].DisplayTitle + '</div>';
                html += '<div class="slideDesc">';
                for (var x = 0; x < jsonObject.DisplayEntries[i].DisplayFields.length; x++) {
                    html += '<strong>' + jsonObject.DisplayEntries[i].DisplayFields[x].FieldName + ':</strong>&nbsp;' + jsonObject.DisplayEntries[i].DisplayFields[x].FieldValue + '<br />';
                }
                html += '</div>';
                html += '</div>';
                html += '<input type="hidden" name="moduleType" value="' + jsonObject.ModuleType + '"/>';
                html += '<input type="hidden" name="entryID" value="' + jsonObject.DisplayEntries[i].EntryID + '"/>';
                html += '<input type="hidden" name="moduleID" value="' + modulePK + '"/>';
                html += '</li>';
            }
        }
    }
    html += '<div style="clear: both;"></div>'; 
    html += '</ul>'; // close thumbs
    html += '</div>'; // close navigation
    html += '<div style="clear: both;"></div>';    
    
    document.getElementById('compModule_Gallery').innerHTML = html;   
    initializeGallery();
}

function initializeGallery() {
    // We only want these styles applied when javascript is enabled
    $('div#compModule_Navigation').css({'width' : '200px', 'float' : 'left'});
    $('div#compModule_Content').css('display', 'block');
    
    // Initially set opacity on thumbs and add
    // additional styling for hover effect on thumbs
    var onMouseOutOpacity = 0.67;
    $('#compModule_Navigation ul.navItems li').opacityrollover({
        mouseOutOpacity: onMouseOutOpacity,
        mouseOverOpacity: 1.0,
        fadeSpeed: 'fast',
        exemptionSelector: '.selected'
    });
    
    $('#slideItems ul.slideItems li').opacityrollover({
        mouseOutOpacity: onMouseOutOpacity,
        mouseOverOpacity: 1.0,
        fadeSpeed: 'fast',
        exemptionSelector: '.selected'
    });
	
	// Initialize FWGallery
    var gallery = $('#compModule_Navigation').FWGallery({        
        slideContainerSel:         '#compModule_Slideshow', 
        controlsContainerSel:      '#compModule_Controls', 
        captionContainerSel:       '#compModule_Caption', 
        loadingContainerSel:       '#compModule_Loading',
		numThumbs: 10,
        renderSSControls: false,
        postback: postback,
        defaultTransitionDuration: 900,

        // accepts a delegate like such: function(prevIndex, nextIndex) { ... }
        onSlideChange:             function(prevIndex, nextIndex) {
			$('#compModule_Navigation ul.navItems').children()

				.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
				.eq(nextIndex).fadeTo('fast', 1.0);
        },
        // accepts a delegate like such: function(callback) { ... }
        onPageTransitionOut: function(callback) {
            $('#compModule_Navigation ul.navItems').fadeTo('fast', 0.0, callback);
        },
        // accepts a delegate like such: function() { ... }
        onPageTransitionIn: function() {
            $('#compModule_Navigation ul.navItems').fadeTo('fast', 1.0);
        },
        voteAlreadyExists: function(entryID, moduleID) {
            if (compModules_readCookie('competitionmodule_' + moduleID + '_' + entryID) != null) {
                return true;
            } else {
                return false;
            }
        }
    });
    
    /**** Functions to support integration of galleriffic with the jquery.history plugin ****/
    
    // PageLoad function
    // This function is called when:
    // 1. after calling $.historyInit();
    // 2. after calling $.historyLoad();
    // 3. after pushing "Go Back" button of a browser
    function pageload(hash) {
        // alert("pageload: " + hash);
        // hash doesn't contain the first # character.
        if (hash) {
            $.FWGallery.gotoSlide(hash);
        } else {
            gallery.gotoIndex(0);
        }
    }
    
    // Initialize history plugin.
    // The callback is called at once by present location.hash. 
    $.historyInit(pageload, "advanced.html");
    
    // set onlick event for buttons using the jQuery 1.3 live method
    $("a.navItem[rel='history']").live('click', function() {
        var hash = this.href;
        hash = hash.replace(/^.*#/, '');

        // moves to a new page. 
        // pageload is called at once. 
        // hash don't contain "#", "?"
        $.historyLoad(hash);

        return false;
    });
}

function createScriptTag(url, callback, error) {
    var scriptTag = document.createElement("script");
    scriptTag.setAttribute("type", "text/javascript");
    scriptTag.setAttribute("id", "dynamicScriptTag");
    scriptTag.setAttribute("src", url);
    if (callback) {
        scriptTag.onload = scriptTag.onreadystatechange = function() {
            if ((!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
                callback();
            }
        };
    }
    var head = document.getElementsByTagName('head')[0];
    if (head)
        head.appendChild(scriptTag);
    else
        document.body.appendChild(scriptTag);
}

function removeScriptTag() {
    var scriptObj = document.getElementById('dynamicScriptTag');

    var head = document.getElementsByTagName('head')[0];
    if (head)
        head.removeChild(scriptObj);
    else
        document.body.removeChild(scriptObj);
}

function createCssLink(href, callback) {
    var cssLink = document.createElement('link');
    cssLink.setAttribute('rel', 'stylesheet');
    cssLink.setAttribute('type', 'text/css');
    cssLink.setAttribute('media', 'screen');
    cssLink.setAttribute('href', href);
    var head = document.getElementsByTagName('head')[0];
    if (head)
        head.appendChild(cssLink);
    else
        document.body.appendChild(cssLink);

    if (callback) waitForCSStoLoad(href, callback);    
}

function waitForCSStoLoad(href, callback) {
    var links = document.getElementsByTagName("link");
    var interval = setInterval(function() {
        for (var i = 0, len = links.length; i < len; ++i) {
            if (links[i].getAttribute("href") === href) {
                clearInterval(interval);
                callback();
            }
        }
    }, 50);
}

function getQuerystring(key, default_) {
    if (default_ == null) default_ = "";
    var scripts = document.getElementsByTagName('script');
    var script = scripts[scripts.length - 1];
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var queryString = regex.exec(script.src);
    if (queryString == null)
        return if_empty;
    else
        return queryString[1];
}

//added for voting

//Cookie Methods

function compModules_createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function compModules_readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function compModules_eraseCookie(name) {
    compModules_createCookie(name, "", -1);
}

//Voting Methods

function submitVote(entryID, moduleID, ranking) {
    if (compModules_readCookie('competitionmodule_' + moduleID + '_' + entryID) != null) {
        alert("cookie exists - rating:" + compModules_readCookie('competitionmodule_' + moduleID + '_' + entryID) + ' competitionmodule_' + moduleID + '_' + entryID);
    } else {
        compModules_createCookie('competitionmodule_' + moduleID + '_' + entryID, ranking, 1);
        createScriptTag(modulesUrlPrefix + 'action=rankentry&callback=submitVoteCallback&modulePK=' + moduleID + '&entryID=' + entryID + '&entryRanking=' + ranking);
        $('#compModule_VotingBox').html('<img src="' + UrlPrefix + 'images/spinner_16.gif" border="0" />'); //spinner
    }
}

function getNextPageHash() {
    if (isNaN(parseInt(self.document.location.hash.substring(1), 0))) {
        return '#2';
    } else {
        return '#' + (parseInt(self.document.location.hash.substring(1), 0) + 1);
    }
}

function submitVoteCallback(jsonObject) {
    removeScriptTag();
    if (jsonObject == '1') {
        $('#compModule_VotingBox').html('<span><b>Thank you for voting on this entry. <a href="' + getNextPageHash() + '">Click here</a> to continue voting.</b></span>');
    } else if (jsonObject == '2') {
        $('#compModule_VotingBox').html('<span><b>We are sorry, but it appears that you have already voted on this entry.</b></span>');
    } else {
        $('#compModule_VotingBox').html('<span><b>Oops - we encountered an error! We are sorry for the inconvenience.</b></span>');
    }
}