﻿jQuery.noConflict()

var SlideShow = {
    csszindex: 100,
    ajaxloadingmsg: "<br><br><br><div align=center><img src='images/shared/ani-busy.gif' /></div>",
    glide: function($, config, showpage, isprev) {
        var selected = parseInt(showpage)
        if (selected >= config.$contentdivs.length) { //if no content exists at this index position
            //alert("No content exists at page " + (selected + 1) + "! Loading 1st page instead.")
            selected = 0
        }
        var $target = config.$contentdivs.eq(selected)



        //Test for toggler not being initialized yet, or user clicks on the currently selected page):
        if (config.$togglerdiv.attr('lastselected') == null || parseInt(config.$togglerdiv.attr('lastselected')) != selected) {
            var $selectedlink = config.$toc.eq(selected)
            config.$next.attr('loadpage', (selected < config.$contentdivs.length - 1) ? selected + 1 + 'pg' : 0 + 'pg')
            config.$prev.attr('loadpage', (selected == 0) ? config.$contentdivs.length - 1 + 'pg' : selected - 1 + 'pg')
            config.$playpause.attr('loadpage', (selected < config.$contentdivs.length - 1) ? selected + 1 + 'pg' : 0 + 'pg')
            if (config.animation == "slide") {
                var startpoint = (isprev == "previous") ? -config.startpoint : config.startpoint
                $target.css(config.leftortop, startpoint).css("zIndex", this.csszindex++) //hide content so it's just out of view before animating it
                var endpoint = (config.leftortop == "left") ? { left: 0} : { top: 0} //animate it into view
                $target.animate(endpoint, config.speed)
            }
            else {

                $target.css("left", "0px").css("top", "0px").css("zIndex", this.csszindex++).hide().fadeIn(config.speed);
            }

            //alert(config.ImageMapLoadedForPages + " selected: " + selected)
            if (config.ImageMapLoadedForPages.indexOf("," + selected + ",") == -1) {
                var intImageFileNo = parseInt($target.attr("ImageFileNo"))
                var intPageNo = parseInt($target.attr("PageNo"))
                SlideShow.getImageMapInfo($, config, intImageFileNo, intPageNo, selected);
            }

            config.$toc.removeClass('selected')
            $selectedlink.addClass('selected')
            config.$togglerdiv.attr('lastselected', selected + 'pg')
        }
    },

    getImageMapInfo: function($, config, myFileNo, myPageNo, selected) {
        var strURL = "SMImageMap.aspx?SMID="
        strURL += getParameterByName("SMID")
        strURL += "&FileNo=" + myFileNo
        strURL += "&PageNo=" + myPageNo
        strURL += "&Rand=" + Math.random()
        //alert(strURL)

        $.ajax({
            url: strURL,          //config.remotecontent
            error: function(ajaxrequest) {
                config.$glider.html('Error fetching image map.<br />Server Response: ' + ajaxrequest.responseText)
            },
            success: function(ImageMapContent) {
                var $target = config.$contentdivs.eq(selected)
                //alert(ImageMapContent)
                $target.append(ImageMapContent)
                var targetDivID = $target.attr("ID")
                $('#' + targetDivID + ' map').each(function() {
                    var intAreaCount = 0;
                    strMapID = $(this).attr("id");
                    //alert("strMapID: " + strMapID);
                    $('#' + strMapID + " area").each(function() {
                        intAreaCount += 1;
                        var oldcoords = $(this).attr("coords");
                        try {
                            var newcoords = SlideShow.AdjustCoordsBasedOnRatio(config.SizePercent/ 100.0, oldcoords);
                            //alert(oldcoords + " new coord: " + newcoords);
                            $(this).attr("coords", newcoords);
                        }
                        catch (e) { }
                    });
                });
                config.ImageMapLoadedForPages += selected + ","
                //alert($target.html())
            }
        })


    },


    AdjustCoordsBasedOnRatio: function(dblratio, coords) {
        var newcoords = '';
        var onecoord = '';
        var intoneCoord = 0;
        var intoneCoordNew = 0;
        //alert(dblratio + " " + coords + " " + LeftOrRight);

        var intCount = 0;
        while (coords.indexOf(',') != -1) {
            onecoord = coords.substring(0, coords.indexOf(','));
            coords = coords.substring(coords.indexOf(',') + 1);
            intoneCoord = parseInt(onecoord);
            intoneCoordNew = Math.floor(intoneCoord * dblratio);
            newcoords += intoneCoordNew + ',';
            intCount++;
        }
        if (coords != '') {
            intoneCoord = parseInt(coords);
            intoneCoordNew = Math.floor(intoneCoord * dblratio);
            newcoords += intoneCoordNew;
        }
        return newcoords;
    },

    getremotecontent: function($, config) {
        config.$playpause.css('visibility', 'hidden')
        this.setwidthandheight($, config)
        config.$glider.html(this.ajaxloadingmsg)

        var strURL = "SMContent.aspx?SMID="
        strURL += getParameterByName("SMID")
        strURL += "&Randomize=" + getParameterByName("Randomize")
        strURL += "&NoOfPages=" + getParameterByName("NoOfPages")
        strURL += "&Rand=" + Math.random()


        $.ajax({
            url: strURL,          //config.remotecontent
            error: function(ajaxrequest) {
                config.$glider.html('Error fetching content.<br />Server Response: ' + ajaxrequest.responseText)
            },
            success: function(content) {
                //alert(content)
                config.$glider.html(content)
                if (config.showbutton == true) {
                    config.$playpause.css('visibility', 'visible')
                }

                SlideShow.setuptoggler($, config)
            }
        })


    },

    aligncontents: function($, config) {
        config.$contentdivs = $("#" + config.gliderid + " ." + config.contentclass)
        config.$contentdivs.css(config.leftortop, config.startpoint).css({ height: config.$glider.height(), visibility: 'visible' }) //position content divs so they're out of view:
    },

    setwidthandheight: function($, config) {
        var contentwidth = config.PageSizeX * config.SizePercent / 100
        var contentheight = config.PageSizeY * config.SizePercent / 100

        var strbgcolor = "#" + config.BGColor
        if ((strbgcolor == "") || (strbgcolor == "#")) { strbgcolor = "#ffffff" }

        config.$contentdivs = $("#" + config.gliderid + " ." + config.contentclass)
        $('.pageimage').css("border", "solid 0px #ffffff").css("width", contentwidth + 'px').css('height', contentheight + 'px')
        config.$contentdivs.css("background-color", strbgcolor)
        config.$contentdivs.css("width", contentwidth + 'px')
        config.$wrapperdiv = $("#" + config.gliderid)
        config.$wrapperdiv.css("width", contentwidth + 'px').css("height", contentheight + 'px') //position content divs so they're out of view:

        $('body').css("background-color", strbgcolor);
        config.heightorwidth = (/up/i.test(config.direction)) ? config.$glider.height() : config.$glider.width() //Get glider height or width based on "direction"
        config.startpoint = (/^(left|up)/i.test(config.direction)) ? -config.heightorwidth : config.heightorwidth //set initial position of contents based on "direction"

        config.$togglerdiv = $("#" + config.togglerid)
        config.$togglerdiv.css(config.halign, config.hno + 'px')
        config.$togglerdiv.css(config.valign, config.vno + 'px')
        //alert(config.halign + " " + config.hno + 'px' + " " + config.valign + " " + config.vno + 'px')

    },

    setuptoggler: function($, config) {
        //.css('border', 'solid ' + config.border + 'px #777777')
        $('.pageimage').bind('click', function(e) {
            if (config.redirectURL != "") {
                //window.parent.document.location.replace(unescape(RedirectURL));
                window.parent.location = unescape(config.redirectURL)
            }
        });

        this.setwidthandheight($, config)
        this.aligncontents($, config)
        config.$togglerdiv.hide()
        config.$toc.each(function(index) {
            $(this).attr('pagenumber', index + 'pg')
            if (index > (config.$contentdivs.length - 1))
                $(this).css({ display: 'none' }) //hide redundant "toc" links
        })
        var $nextandprev = $("#" + config.togglerid + " .next, #" + config.togglerid + " .prev")
        $nextandprev.click(function(event) { //Assign click behavior to 'next' and 'prev' links
            SlideShow.glide($, config, this.getAttribute('loadpage'), this.getAttribute('buttontype'))
            event.preventDefault() //cancel default link action
        })
        var $playpause = $("#" + config.togglerid + " .playpause")
        $playpause.click(function(event) { //Assign click behavior to 'play'
            if (config.autorotate == false || config.totalsteps == 0 || config.stepcount >= config.totalsteps) {

                SlideShow.cancelautorotate(config.togglerid)
                // SlideShow.glide(config, this.getAttribute('loadpage'), this.getAttribute('buttontype'))
                config.autorotateconfig[0] = getIntParameterByName("Interval", config.autorotateconfig[0], true)
                config.autorotateconfig[1] = getIntParameterByName("NoOfCycles", config.autorotateconfig[1], true)
                config.autorotate = true
                config.stepcount = 0
                //alert(" here" + config.autorotateconfig[1])
                config.totalsteps = config.$contentdivs.length * config.autorotateconfig[1]
                SlideShow.autorotate(config)
                $("#imgPlayPause").attr("src", "images/shared/pause.png").attr("alt", "pause")
            }
            else {
                config.autorotate = false
                config.totalsteps = 0;
                SlideShow.cancelautorotate(config.togglerid)
                $("#imgPlayPause").attr("src", "images/shared/play.png").attr("alt", " play ")
            }


        })


        config.$toc.click(function(event) { //Assign click behavior to 'toc' links
            SlideShow.glide($, config, this.getAttribute('pagenumber'))
            event.preventDefault()
        })
        config.$togglerdiv.fadeIn(600, function() {
            SlideShow.glide($, config, config.selected)
            if (config.autorotate == true) { //auto rotate contents?
                config.stepcount = 0 //set steps taken
                //alert(" config.$togglerdiv.fadeIn " + config.autorotateconfig[1])
                config.totalsteps = config.$contentdivs.length * config.autorotateconfig[1] //Total steps limit: num of contents x num of user specified cycles)
                SlideShow.autorotate(config)
            }
            else {
                config.$playpauseimage = config.$playpause.find('.imagebutton').attr("src", "images/shared/play.png").attr("alt", " play ")
            }
        })

    },

    autorotate: function(config) {
        var rotatespeed = config.speed + config.autorotateconfig[0]
        window[config.togglerid + "timer"] = setInterval(function() {
            if (config.totalsteps > 0 && config.stepcount >= config.totalsteps) {
                clearInterval(window[config.togglerid + "timer"])
                config.$playpauseimage = config.$playpause.find('.imagebutton').attr("src", "images/shared/play.png").attr("alt", " play ")
            }
            else {
                config.$next.triggerHandler('click')
                config.stepcount++
            }
        }, rotatespeed)
    },

    cancelautorotate: function(togglerid) {
        if (window[togglerid + "timer"]) {
            clearInterval(window[togglerid + "timer"])
        }
    },

    getCookie: function(Name) {
        var re = new RegExp(Name + "=[^;]+", "i") //construct RE to search for target name/value pair
        if (document.cookie.match(re)) //if cookie found
            return document.cookie.match(re)[0].split("=")[1] //return its value
        return null
    },

    setCookie: function(name, value) {
        document.cookie = name + "=" + value
    },

    init: function(config) {
        jQuery(document).ready(function($) {

            config.autorotateconfig[0] = getIntParameterByName("Interval", config.autorotateconfig[0], true)

            config.autorotateconfig[1] = getIntParameterByName("NoOfCycles", config.autorotateconfig[1], true)

            config.speed = getIntParameterByName("Speed", config.speed, true)

            config.animation = getParameterByNameWValueRange("Animation", ",fade,slide,")
            config.BGColor = getParameterByName("BGColor")
            config.direction = getParameterByNameWValueRange("SlidingDirection", ",updown,downup,leftright,rightleft,", "rightleft")
            config.autorotate = getBoolParameterByName("AutoRotate", true)
            config.SizePercent = getIntParameterByName("SizePercent", 100, true)
            config.PageSizeX = getIntParameterByName("PageSizeX", 445, true)
            config.PageSizeY = getIntParameterByName("PageSizeY", 576, true)
            config.halign = getParameterByNameWValueRange("ButtonHAlign", ",left,right", "right")
            var intHNo = -12
            if (config.halign == 'right') {
                intHNo = 3
            }
            config.hno = getIntParameterByName("HNo", intHNo, false)
            config.valign = getParameterByNameWValueRange("ButtonVAlign", ",top,bottom", "bottom")
            config.vno = getIntParameterByName("VNo", 0, false)
            config.showbutton = getBoolParameterByName("ShowButton", false)
            config.redirectURL = getParameterByName("RedirectURL")

            //config.$pause = config.$togglerdiv.find('.pause')

            config.$glider = $("#" + config.gliderid)
            config.$togglerdiv = $("#" + config.togglerid)
            config.$toc = config.$togglerdiv.find('.toc')
            config.$next = config.$togglerdiv.find('.next')
            config.$prev = config.$togglerdiv.find('.prev')
            config.$playpause = config.$togglerdiv.find('.playpause')
            config.$playpauseimage = config.$playpause.find('.imagebutton')

            config.$prev.attr('buttontype', 'previous')
            var selected = (config.persiststate) ? SlideShow.getCookie(config.gliderid) : config.selected
            config.selected = (isNaN(parseInt(selected))) ? config.selected : selected //test for cookie value containing null (1st page load) or "undefined" string	
            config.leftortop = (/up/i.test(config.direction)) ? "top" : "left" //set which CSS property to manipulate based on "direction"
            config.ImageMapLoadedForPages = ",";
            //if (typeof config.remotecontent != "undefined" && config.remotecontent.length > 0)
            SlideShow.getremotecontent($, config)
            //else
            //    SlideShow.setuptoggler($, config)
            $(window).bind('unload', function() { //clean up and persist
                config.$togglerdiv.unbind('click')
                config.$toc.unbind('click')
                config.$next.unbind('click')
                config.$prev.unbind('click')
                config.$playpause.unbind('click')
                if (config.persiststate)
                    SlideShow.setCookie(config.gliderid, config.$togglerdiv.attr('lastselected'))
                config = null

            })
        })
    }
}


function JQEventLog(strURL) {

    jQuery.ajax({

        url: strURL,
        error: function(ajaxrequest) {
            $('#divCatalogContent').html('Error logging event.<br />Server Response: ' + ajaxrequest.responseText);
        },
        success: function(strResponse) {
        //alert(strURL);
        }
    })

}


function showexternal(externalurl, eventlogurl) {
    var property = "";
    //alert(externalurl + " " + eventlogurl);

    var bolShowLinkInNewWindow = getBoolParameterByName("ShowLinkInNewWindow", false);
    if ((externalurl.indexOf('http://') == -1) && (externalurl.indexOf('https://') == -1)) {
        externalurl = 'http://' + externalurl;
    }

    if ((window.parent != null) && (bolShowLinkInNewWindow == false)) {
        //alert(externalurl);
        window.parent.location = unescape(externalurl);

    }
    else {
        var property = "resizable=1, width=800, height=600";
        var newwin = window.open(externalurl, '', property);
        //	var wincatalog = window.open("OpenPage.aspx?CatalogOID=" + CatalogOID + "&SupplierID=168664&ShowPage=" + ShowPage + "&Password=" + Password, 'ActiveMerchandiser', property);
        
    }

    JQEventLog(eventlogurl);
}

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null) { return ""; }
    else { return results[1]; }

}

function getBoolParameterByName(name, defaultvalue) {
    var strvalue = getParameterByName(name).toLowerCase();
    var bolvalue = defaultvalue;
    if (strvalue == "true") {
        bolvalue = true;
    }
    else if (strvalue == "false") {
        bolvalue = false;
    }
    return bolvalue;

}

function getParameterByNameWValueRange(name, valuerange, defaultvalue) {
    var strvalue = getParameterByName(name).toLowerCase();
    if (valuerange.indexOf("," + strvalue + ",") == -1) {
        strvalue = defaultvalue;
    }

    return strvalue;

}

function getIntParameterByName(name, defaultvalue, bolmustpositive) {
    var intvalue = defaultvalue;
    var strvalue = getParameterByName(name);
    if (strvalue != "") {
        try {
            intvalue = parseInt(strvalue);
        }
        catch (ex) { }
    }

    if ((bolmustpositive == true) && (intvalue < 0)) intvalue = defaultvalue;
    return intvalue;
}
