/**********************************
' TTT -  http://www.tttcompany.com
' Copyright (c) 1992-2009
' by TTT Corporation
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
' of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
' DEALINGS IN THE SOFTWARE.
***************************/
//var inPageOptions = { slideshowGroup: 'first-group', outlineType: null, allowSizeReduction: false, wrapperClassName: 'in-page controls-in-heading floating-caption', captionOverlay: { position: 'top right', offsetY: -15, offsetX: -10, relativeTo: 'expander' }, useBox: true, width: 860, height: 0, targetX: 'gallery-area 5px', targetY: 'gallery-area 10px', autoplay: false };
//var inPageStartOptions = { slideshowGroup: 'first-group', outlineType: null, allowSizeReduction: false, wrapperClassName: 'in-page controls-in-heading floating-caption', captionOverlay: { position: 'top right', offsetY: -15, offsetX: -10, relativeTo: 'expander' }, useBox: true, width: 860, height: 0, targetX: 'gallery-area 5px', targetY: 'gallery-area 10px', autoplay: true };
/*********************************
*    LIGHTBOX
*********************************/
var lbOption;
$(document).ready(function() {

    if ($('#gallery-container').length==0) return false;    
    //STOP
    galleryLayout = $('#gallery-container').layout({
        applyDefaultStyles: true
        , closable: true	            // pane can open & close
        , togglerLength_open: 35		// WIDTH of toggler on north/south edges - HEIGHT on east/west edges
		, togglerLength_closed: 35      // "100%" OR -1 = full height
		, paneClass: "pane" 		    // default = 'ui-layout-pane'
		, resizerClass: "resizer"	    // default = 'ui-layout-resizer'
		, togglerClass: "toggler"	    // default = 'ui-layout-toggler'
		, fxName: "slide"		        // none, slide, drop, scale
		, fxSpeed: "slow"		        // slow, normal, fast, 1000, nnn
		, spacing_open: 5
		, spacing_closed: 5
		, west__size: 180
		, west__onresize: function() { $("#accordion").accordion("resize"); applyStyle(galleryStyle, false); }
		, west__onclose: function() { applyStyle(galleryStyle, false); }
		, west__onopen: function() { applyStyle(galleryStyle, false); }

    });    
    $("#accordion").accordion({
        fillSpace: true
    , icons: { header: "accordion-header", headerSelected: "ui-icon-circle-arrow-s" }
    });
    /**********************
    ALBUM TREE 
    **********************/
    $.ui.dynatree.nodedatadefaults["activate"] = false;
    $.ui.dynatree.nodedatadefaults["focus"] = false;
    $.ui.dynatree.nodedatadefaults["expand"] = false;
    $.ui.dynatree.nodedatadefaults["select"] = false;    
    $("#album-tree").dynatree({
        rootVisible: false,        
        persist: false, //true, let VB code handles cookie
        clickFolderMode: 3,
        selectMode: 2,        
        fx: { height: "toggle", duration: 200 },
        imagePath: rooturl,
        //autoCollapse: true,
        activeVisible: true,
        onPostInit: function(isReloading, isError) {
            // 'this' is the current tree
            // isReloading is set, if status was read from existing cookies
            // isError is only used in Ajay mode
            // Fire an onActivate() event for the currently active node
            this.reactivate();
        },
        onActivate: function(dtnode) {           
            //var isInitializing = dtnode.tree.isInitializing(); // Tree loading phase
            //var isReloading = dtnode.tree.isReloading(); // Loading phase, and reading status from cookies
            var isUserEvent = dtnode.tree.isUserEvent(); // Event was triggered by mouse or keyboard
            if (isUserEvent) viewPictures(dtnode.data.key);        
        },        
        children: albumdata
    });
    bindTreeMenu();
    bindContextMenu();     
    lbOption = {
        overlayOpacity: 0.3,    
        initialWidth: 250,
        initialHeight: 250,         
        easing: "easeOutElastic",        
        captionAnimationDuration: 1,        
        counterText: "Image {x} sur {y}", 
        //overlayFadeDuration: 400,  
        //resizeDuration
        //resizeEasing       
        //closeKeys: [27, 70],        
        //nextKeys: [39, 83],
        loop: true   
   };   
   //alert('ready');
    $("#pictures-area .lightbox").slimbox(lbOption);    
    addEventListener(document, window.opera ? 'keypress' : 'keydown', keyHandler);
    // for gallery breadcrumb since version 2.0
    //jQuery("#galleryBreadCrumb").jBreadCrumb();  
});

///**********************
//HIGHSLIDE    
//**********************/
////$(document).ready(function() {
//    hs.graphicsDir = graphicsDir;
//    hs.outlineType = 'rounded-white';
//    hs.transitions = ['expand', 'crossfade'];
//    hs.allowMultipleInstances = false;
//    //hs.dimmingOpacity = 0.7;
//    //easing = 'easeInBack';
//    easingClose = 'easeInQuad';
//    hs.fadeInOut = true;
//    hs.align = 'center';
//    hs.restoreCursor = null;
//    hs.loadingText = 'Loading...';
//    hs.showCredits = false;
//    //
//    hs.addSlideshow({
//        slideshowGroup: 'first-group',
//        interval: 5000,
//        repeat: false,
//        useControls: true,
//        overlayOptions: { position: 'top left', offsetX: -10, offsetY: 15, relativeTo: 'expander' },
//        thumbstrip: { position: 'top center', offsetX: 0, offsetY: -40, mode: 'horizontal', relativeTo: 'expander' }
//    });
//    hs.Expander.prototype.onImageClick = function() {
//        if (/in-page/.test(this.wrapper.className)) return hs.next();
//    };
//    hs.Expander.prototype.onBeforeClose = function() {        
//        if (!this.slideshow) return;        
//        cpage++;       
//        if (this.a.id=='end') $target.viewSlideshow(cpage);
//        else
//        { EndSlideshow(); $target.gotoPage(cpage); }
//    };
//    //hs.addEventListener(window, 'resize', function() { var i, exp; hs.page = hs.getPageSize(); for (i = 0; i < hs.expanders.length; i++) { exp = hs.expanders[i]; if (exp) { var x = exp.x, y = exp.y; exp.tpos = hs.getPosition(exp.el); x.calcThumb(); y.calcThumb(); x.pos = x.tpos - x.cb + x.tb; x.scroll = hs.page.scrollLeft; x.clientSize = hs.page.width; y.pos = y.tpos - y.cb + y.tb; y.scroll = hs.page.scrollTop; y.clientSize = hs.page.height; exp.justify(x, true); exp.justify(y, true); exp.moveTo(x.pos, y.pos); } } });
////});

/**********************
TREE MENU & CONTEXT MENU    
**********************/
// Add context menu to tree nodes:
function bindTreeMenu() {
    $(".ui-dynatree-folder")
    .destroyContextMenu() // unbind first, to prevent duplicates
    .contextMenu({ menu: "albumMenu" }, function(action, el, pos) { var dtnode = el.attr("dtnode"); doGalleryTasks(dtnode.data.key, action) });
};

function bindContextMenu() {
    $(".album-menu")
        .contextMenu({ menu: "albumMenu", leftButton: true }, function(action, el, pos) { var id = el.attr("id"); doGalleryTasks(id, action) });
    $(".picture")
        .contextMenu({ menu: "fileMenu" }, function(action, el, pos) { var id = el.attr("id"); doGalleryTasks(id, action) });

};

function selectAlbum(id) {
    //alert('album');
    if (id == rootalbumid) id = '0';
    if ($target != undefined) {
        $(albumcontrolid).val(id);
        //alert($(albumcontrolid).val);
        $target.viewAlbum();
    }
}

function viewPictures(id) {
    if (id == rootalbumid) id = '0';
    if ($target != undefined) {
        $(albumcontrolid).val(id);
        $target.viewPictures();
    }
}

function doGalleryTasks(id, action) {
    var editURL = editurl.replace('myid', id);    
    switch (action) {
        case "open":
            viewPictures(id);
            return false
            break;
        case "fileedit":
            //alert(editURL);
            editURL = editURL.replace('mycontrolkey', 'FileEdit');
            editURL = editURL.replace('mymode', 'Edit');
            window.location.href = editURL;
            return false
            break;
        case "filedownload":
            editURL = editURL.replace('mycontrolkey', '');
            editURL = editURL.replace('mymode', 'Download');
            alert('feature is under construction!');
            //window.location.href = editURL;
            return false
            break;
        case "albumedit":
            editURL = editURL.replace('mycontrolkey', 'AlbumEdit');
            editURL = editURL.replace('mymode', 'Edit');
            window.location.href = editURL;
            return false
            break;
        case "albumadd":
            editURL = editURL.replace('mycontrolkey', 'AlbumEdit');
            editURL = editURL.replace('mymode', 'Add');
            window.location.href = editURL;
            return false
            break;
        case "fileadd":
            editURL = editURL.replace('mycontrolkey', 'FileAdd');
            editURL = editURL.replace('mymode', 'Add');
            window.location.href = editURL;
            return false
            break;
        case "filedetail":
//            var url = fileurl.replace('myid', id); 
//            window.location.href = url;
            var $container = $("#picture-container");
            $container.viewImage(id);
            //return false
            break;
        case "albumurl":
            var url = albumurl.replace('myid', id); 
            $.copy(url);
            break; 
        case "fileurl":
            var url = fileurl.replace('myid', id); 
            $.copy(url);
            break;  
        case "viewcomment":
            var $container = $("#picture-container");
            $container.ViewPopupComment(id);
            break;                
        case "cancel":
            return false
            break;
        
        default:
            window.location.href = action;
    }
}

// filter argument
$.fn.requestData = function(fdata, prefix) {
    var arg = ''; //'<filter>';
    for (var i = 0; i < fdata.length; i++) {
        if ((fdata[i].n != undefined) && (fdata[i].c != undefined)) {
            var ctlname = prefix + fdata[i].c
            arg += '<ctl' + fdata[i].n + '>';
            arg += ctlname;
            arg += '</ctl' + fdata[i].n + '>';

            arg += '<' + fdata[i].n + '>';
            var ctl = document.getElementById(ctlname);
            if (ctl != undefined) {
                var type = ctl.type;
                var val = ctl.value;
                if (type == "textarea") {
                    // Firefox has the bad habit of altering the "\r\n" of a textarea to "\n",		
                    // so convert all single "\n" to "\r\n"		
                    val = val.split("\r\n").join("\n").split("\n").join("\r\n");
                }
                if (type == "checkbox" || type == "radio") {
                    val = ctl.checked;
                }
                if (type == "select-multiple") {
                    for (var j = 0; j < ctl.options.length; j++)
                        if (ctl.options[j].selected) {
                        val = ctl.options[j].value;
                    }
                }
                arg += val;
                // save style value here // 

                if (fdata[i].n == 'style') galleryStyle = val;
                if (fdata[i].n == 'view') galleryView = val;
            }
            arg += '</' + fdata[i].n + '>';
        }
    }
    return arg;
}

// viewcomment
$.fn.ViewPopupComment = function(fileid){
    
    
    var newPopup = PopupDiv;
    newPopup.PopupBackground = "backgroundPopup";
    newPopup.PopupContent = "divPopupContent";
    newPopup.itemid = fileid;
    newPopup.handlerUrl = commentUrl;
    newPopup.ShowPopup();
    //$("#CommentPopup").show();
    $(document).ready(function(){
        var url = commentUrl; 
        
        url += "&fileid=" + fileid;
        url += "&action=getpicture";
        
        $.post(url,"",function(returndata){ 
            $("#divPictureInfo").html(returndata);             
        })  
        
        url = commentUrl;
        url += "&fileid=" + fileid;
        url += "&action=list";
        
        $.post(url,"",function(returndata){ 
            $("#CommentContent").html(returndata);            
        })  
    })
    return false;
}

// viewalbum
$.fn.viewAlbum = function () {
    cpage = 1;
    var fdata = this.requestData(fcontrols, prefix);
    fdata += '<currentpage>' + cpage + '</currentpage>';
    fdata = '<viewalbum>' + fdata + '</viewalbum>';
    this.ajaxPost(url, fdata, true);
}

// view album page
$.fn.gotoAlbumPage = function (currentpage) {
    cpage = currentpage;
    var fdata = this.requestData(fcontrols, prefix);
    fdata += '<currentpage>' + currentpage + '</currentpage>';
    fdata = '<gotoalbumpage>' + fdata + '</gotoalbumpage>';
    this.ajaxPost(url, fdata, true);
}

// view Picture in album
$.fn.viewPictures = function () {
    cpage = 1;
    var fdata = this.requestData(fcontrols, prefix);
    fdata += '<currentpage>' + cpage + '</currentpage>';
    fdata = '<viewpicture>' + fdata + '</viewpicture>';
    this.ajaxPost(url, fdata, true);
}

// view album page
//$.fn.gotoPage = function(scope, currentpage) {
$.fn.gotoPage = function(currentpage) {
    cpage = currentpage;
    var fdata = this.requestData(fcontrols, prefix);
    //fdata += '<scope>' + scope + '</scope>';
    fdata += '<currentpage>' + currentpage + '</currentpage>';
    fdata = '<gotopage>' + fdata + '</gotopage>';
    this.ajaxPost(url, fdata, true);
}

$.fn.applyFilter = function(scope) {
    if (scope=='all')
    $(albumcontrolid).val('0');
    //alert($(albumcontrolid).val());
    cpage = 1;
    var fdata = this.requestData(fcontrols, prefix);
    //fdata += '<scope>' + scope + '</scope>';    
    fdata += '<currentpage>' + cpage + '</currentpage>';
    fdata = '<applyfilter>' + fdata + '</applyfilter>';
    this.ajaxPost(url, fdata, true);
}

$.fn.removeFilter = function() {
    for (var i = 0; i < fcontrols.length; i++) {
        if (fcontrols[i].c != undefined) {
            var ctlname = prefix + fcontrols[i].c;
            var ctl = document.getElementById(ctlname);
            if (ctl != undefined && fcontrols[i].n != 'pagesize' && fcontrols[i].n != 'sort' && fcontrols[i].n != 'desc' && fcontrols[i].n != 'view' && fcontrols[i].n != 'style') {
                if (ctl.value.match(/^\d+$/) == null) ctl.value = ''
                // do not remove albumid
                //else ctl.value = '0';
            }
        }
    }
    cpage = 1;
    var fdata = this.requestData(fcontrols, prefix);
    fdata += '<currentpage>' + cpage + '</currentpage>';
    fdata = '<removefilter>' + fdata + '</removefilter>';
    this.ajaxPost(url, fdata, true);
}

// view single image detail
$.fn.viewImage = function(id) {
    $("#gallery-header").hide();    
    $("#gallery-container").fadeOut(500, function() {
        var fdata = '<id>' + id + '</id>';
        fdata = '<viewimage>' + fdata + '</viewimage>';
        var $pcontainer = $("#picture-container");   
        $.post(url, fdata, function(data) {            
            $pcontainer.html(JSDecode(data)).fadeIn(1000, function(data) {
                $("#stars-wrapper").stars({inputType: "select", disabled: true});
            });
        });
    });
}

$.fn.viewComment = function(id) {    
    $(this).toggleClass("active");    
    if ($(this).hasClass("active")) {
        $(this).next("div").getComment(id, 1);        
    }
    else
    $(this).next("div").slideToggle("normal");
}

$.fn.getComment = function(id, currentpage) {
    var fdata = '<id>' + id + '</id>';
    fdata += '<currentpage>' + currentpage + '</currentpage>'; 
    fdata = '<viewcomment>' + fdata + '</viewcomment>'; 
    var $container = $(this); 
    $.post(url, fdata, function(data) {
        $container.html(JSDecode(data)).css("display", "block");
    });
}

$.fn.viewEXIF = function(id) {
    $(this).toggleClass("active");    
    if ($(this).hasClass("active") && $(this).next("div").html()=='') {
        var fdata = '<id>' + id + '</id>';        
        fdata = '<viewexif>' + fdata + '</viewexif>'; 
        alert($(this).width());
        var $container = $(this).next("div");  
        $.post(url, fdata, function(data) {
            $container.html(JSDecode(data)).css("display", "block");
        });      
    }
    else
    $(this).next("div").slideToggle("normal");
}

// return to album view mode from picture detail view
function galleryHome(id) {   
    if (!id) id = '0';
    $(albumcontrolid).val(id); 
    //$("#picture-container").effect('drop', {}, 1000, function() {
    //$("#picture-container").html("").fadeOut(200, function() {
    $("#picture-container").html("").fadeOut(500)
        $("#gallery-header").fadeIn(100 , function() { 
            $("#gallery-container").fadeIn(1000, function() { 
                //selectAlbum(id);              
            }); 
        });
    //}); 
}
/*********************************
    CYCLE
*********************************/
var ssOption = {
    speed: 2000, 
    timeout: 2000,    
    pagerEvent: 'mouseover', 
    fastOnEvent: true, 
    next: '#next', 
    prev: '#prev',     
    easing: 'easeInBack', //linear, swing, easeInBack, easeOutQuart
    fx: 'fade,blindX,toss,wipe',  //fx: 'toss,fade,wipe,blindX', 
    randomizeEffects: false, 
    sync: true,
    before: onBefore, //function(c,n,o) {$(o.caption).html(n.title);}, 
    after: onAfter,
    autostop: 1, 
    end: appendSlideshow, 
    //caption: '#title', 
    pager: '#nav',   
    requeueOnImageNotLoaded: false, 
    pagerAnchorBuilder: function(idx, slide) { return '<li><a href="#"><img src="' + slide.src + '" width="28" height="28" /></a></li>';}
    };

$.fn.viewSlideshow = function(currentpage) {
    //spage = currentpage; 
    cpage = currentpage;
    galleryLayout.hide("west");   
    //galleryLayout.panes.west.css("display")
    $("#gallery-header").hide();   
    var fdata = this.requestData(fcontrols, prefix);
    fdata += '<currentpage>' + currentpage + '</currentpage>';    
    fdata = '<slideshow>' + fdata + '</slideshow>';
    var $container = this;
     $(".picture-strip").effect('drop', {}, 1000, $container.loadIndicator());
    $.post(url, fdata, function(data) {        
        $container.animate({ height: 'hide' }, 300, function() {
            $container.html(JSDecode(data)).animate({ height: 'show' }, 600, function() {    
                var $pictures = $("#pictures");                            
                $pictures.cycle(ssOption); 
                var navW = ($pictures.children().length * 33) + 'px';                
                $("#nav").css("width", navW);
            });
        });
    });
}  

function appendSlideshow() {    
    //spage++;
    cpage++;   
    var fdata = $('#pictures').requestData(fcontrols, prefix); 
    fdata += '<currentpage>' + cpage + '</currentpage>';
    fdata += '<append>true</append>';
    fdata = '<slideshow>' + fdata + '</slideshow>';     
    $.post(url, fdata, function(data) { 
        var $ss = $('#pictures');        
        $ss.fadeOut(1000, function() { 
        $ss.css({left: '0px', width: '0px'});
        $ss.empty();
        $ss.append(JSDecode(data)).fadeIn(500, function() {  
            $('#nav').empty();              
            $ss.cycle(ssOption); 
            var navW = ($ss.children().length * 33) + 'px';                
            $('#nav').css("width", navW);
        });
        });
    });    
}

function onAfter(curr,next,o) {
     var $pictures = $("#pictures");   
     var pW = $pictures.parent().width();
     var cW = next.width + 20; 
    var cL = (pW / 2) - (cW / 2);     
    $pictures.animate({width: (pW - cL) + 'px', left: cL + 'px'}, 500); 
     var $title = $("#title");
     $title.html(next.title);
     var $caption = $("#caption");       
     $caption.animate({ height: 'hide' }, 10, function() {
            $caption.html(next.alt).animate({ height: 'show' }, 1000)
     });      
}

function onBefore(curr, next, opts) {
//var $pictures = $("#pictures");   
//     var pW = $pictures.parent().width();
//     var cW = next.width + 20;
//     //var cL = ((pW - cW) / 2);   
//     var cL = (pW / 2) - (cW / 2);     
//    $pictures.animate({width: (pW - cL) + 'px', left: cL + 'px'}, 500);  
} 

function slideshowAction(action) { 
    var $pictures = $('#pictures');
    switch (action) {
        case "prev":
            $("#prev").click();            
            return false
            break;
        case "next":
            $("#next").click(); 
            return false
            break;
        case "pause":    
            $pictures.cycle(action);        
            $("#pause").css("display", "none");
            $("#play").css("display", "block");
            return false
            break;
        case "resume":  
            $pictures.cycle(action);
            $("#pause").css("display", "block");
            $("#play").css("display", "none");
            return false
            break;
        case "close":  
            //check to make sure it's in slideshow mode     
            if ($("#gallery-header").css('display')=="none") {  
                $target.animate({ height: 'hide' }, 500, function() {
                    $("#nav").remove();
                    $pictures.remove();  
                    $pictures.cycle('end');
                    $pictures.cycle = false;   
                    galleryLayout.show("west", 1000) 
                    $("#gallery-header").fadeIn(1000 , function() {                                            
                        $target.gotoPage(cpage);                         
                    });  
                });
            }                
            return false
            break;
    }
}

// global ajax post function
$.fn.ajaxPost = function(url, requestdata, isDisplay) {
    removeEventListener(document, window.opera ? 'keypress' : 'keydown', keyHandler);
    addEventListener(document, window.opera ? 'keypress' : 'keydown', keyHandler);
    var $container = this;
    var containerWidth = $container.width(); // get container dimension before apply any effect
    var containerHeight = $container.height();
    $("#footer").html("");
    $(".picture-strip").effect('drop', {}, 1000, $container.loadIndicator());
    $.post(url, requestdata, function(data) {
        $container.animate({ height: 'hide' }, 300, function() {
            $container.html(JSDecode(data)).animate({ height: 'show' }, 600, function() {
                if (isDisplay) {
                    //$('#pictures-area .lightbox').lightBox(lbOption);
                     $("#pictures-area .lightbox").slimbox(lbOption);
                    bindContextMenu();
                    //setLayout(containerWidth, containerHeight);
                    //setView(galleryView);
                    applyStyle(galleryStyle, false);
                    
                }
            });
        });
    });
}

$.fn.loadIndicator = function() {
    var $loadingIndicator = $('<img/>')
        .attr({ 'src': 'http://www.lairai.com/DesktopModules/TTT.Gallery/images/loading.gif', 'alt': 'Loading. Please wait.' })
        .addClass('loadingimage')
        .appendTo(this);
    // set position for loading image in the center of parent container
    var x = (this.width() / 2);
    var y = (this.height() / 2);
    $loadingIndicator.css('top', y);
    $loadingIndicator.css('left', x);
    //return $loadingIndicator;
}

$.fn.resetStyle = function(newClass) {
    this.removeClass();
    this.addClass(newClass);
}

function setView(view) {
    galleryView = view;
    var $container = $("#gallery-container");
    var $content = $("#content-area");
    var containerHeight = '';
    var w = '';
    var styleSet = false;
    switch (view) {
        case "Standard":
            $(".display").fadeOut(10, function() {
                w = (99.9 / stripWidth) + '%';
                $(this).css("width", w).removeClass().addClass("display thumb-view").fadeIn(100, function() {
                    containerHeight = (28 + ($(this).height() * stripHeight) + 28) + 'px';
                    if (!styleSet) {
                        $content.css('width', '100%');
                        applyStyle(galleryStyle, false);
                        styleSet = true;
                    }
                });
            });
            break;
        case "Detail":
            $(".display").fadeOut(10, function() {
                w = '99.9%';
                $(this).css("width", w).removeClass().addClass("display detail-view").fadeIn(100, function() {
                    containerHeight = (28 + ($(this).height() * stripHeight * stripWidth) + 28) + 'px';
                    if (!styleSet) {
                        $content.css('width', '97.5%');
                        applyStyle(galleryStyle, false);
                        styleSet = true;
                    }
                });
            });
            break;
        case "List":
            $(".display").fadeOut(10, function() {
                w = '99.9%';
                $(this).css("width", w).removeClass().addClass("display list-view").fadeIn(100, function() {
                    containerHeight = (28 + ($(this).height() * stripHeight) + 28) + 'px';
                    if (!styleSet) {
                        $content.css('width', '100%');
                        applyStyle(galleryStyle, true);
                        styleSet = true;
                    }
                });
            });
            break;
    }
}

function applyStyle(style, changeStyle) {
    galleryStyle = style;   // save style name for resize later
    if (!style || $(".picture-strip").length == 0) return false
    if (galleryView == "List") style = "";
    //
    var $pictureStrip = $(".picture-strip");
    var $picture = $(".picture");
    var $pictureSpan = $(".picture-strip span");
    //
    var tripLeft = $(".picture-strip:eq(0)").position().left;
    var pictureLeft = $(".picture:eq(0)").position().left;
    var left = 0;
    //    
    if (changeStyle) $pictureSpan.removeClass();
    $pictureSpan.hide();
    switch (style) {
        case "":
            break;
        case "pin":
            left = (pictureLeft - tripLeft) + 50;
            $pictureSpan.css('left', left).addClass(style);
            $pictureSpan.animate({ opacity: 'show' }, 500)
            break;
        case "floral-corner":
            left = (pictureLeft - tripLeft) - 15;
            $pictureSpan.css('left', left).addClass(style);
            $pictureSpan.animate({ width: 'show' }, 1000)
            break;
        case "paper-clip":
            left = (pictureLeft - tripLeft);
            $pictureSpan.css('left', left).addClass(style);
            $pictureSpan.animate({ height: 'show' }, 500)
            break;
        case "mask":
            left = (pictureLeft - tripLeft);
            $pictureSpan.css('left', left).addClass(style);
            $pictureSpan.animate({ width: 'show', height: 'show' }, 1000)
            break;
        case "mask-darken":
            left = (pictureLeft - tripLeft) + 3;
            $pictureSpan.css('left', left);
            if (changeStyle) {
                $picture.resetStyle("picture");
                $pictureStrip.resetStyle("picture-strip");
                $pictureSpan.addClass("style-mask-darken");
                $picture.addClass("picture-mask");
                $pictureStrip.addClass("picture-strip-darken");
                $(".picture img").css("border", "none");
            }
            break;
        case "watercolor":
            left = (pictureLeft - tripLeft) - 6;
            $pictureSpan.css('left', left);
            if (changeStyle) {
                $picture.resetStyle("picture");
                $pictureStrip.resetStyle("picture-strip");
                $pictureSpan.addClass("style-watercolor");
                $pictureStrip.addClass("picture-strip-white");
                $picture.addClass("picture-mask");
                $(".picture img").css("border", "none");
            }
            break;
        case "golden-frame": // -15            
            left = (pictureLeft - tripLeft) - 15;
            $pictureSpan.css('left', left);
            if (changeStyle) {
                $picture.resetStyle("picture");
                $pictureStrip.resetStyle("picture-strip");
                $pictureSpan.addClass("style-golden-frame");
                $pictureStrip.addClass("picture-strip-red");
                $(".picture img").css("border", "none");
            }
            break;
        case "round-corner":
            left = (pictureLeft - tripLeft) + 2;
            $pictureSpan.css('left', left);
            if (changeStyle) {
                $picture.resetStyle("picture");
                $pictureStrip.resetStyle("picture-strip");
                $pictureStrip.addClass("picture-strip-white");
                $pictureSpan.addClass("style-round-corner");
                $(".picture img").css("border", "none");
            }
            break;
        case "ancient":
            left = (pictureLeft - tripLeft) - 6;
            $pictureSpan.css('left', left);
            if (changeStyle) {
                $picture.resetStyle("picture");
                $pictureStrip.resetStyle("picture-strip");
                //$pictureStrip.addClass("picture-strip-white");
                $pictureSpan.addClass("style-ancient");
                $(".picture img").css("border", "none");
            }
            break;
        default:
            return false
    }
    //if (changeStyle) $pictureSpan.animate({ width: 'show' }, 1000)
    //if (animate) $pictureSpan.animate({ width: 'show' }, 1000)
    return false
}

function keydownfn(e) {
    if (e.keyCode == 13) {
        $target.applyFilter('all');
        if (window.event) {
            window.event.returnValue = false;
        }
        else {
            e.preventDefault();
        }
    }
}

function JSDecode(s) {
    s = s.replace('\"', '"');
    s = s.replace("\'", "'");
    s = s.replace("\/", "/");
    return s;
}

function keyHandler(e) {
    if (!e) e = window.event;
    if (!e.target) e.target = e.srcElement; // ie
    if (typeof e.target.form != 'undefined') return true; // form element has focus
    //alert(e.keyCode);
    var op = null;
    switch (e.keyCode) {
        case 32: // Space
            //alert('space:' + cpage);	
            op = 2;           
            var $play = $("#play");                    
            if ($play.css("display")!='none') $play.click();
            else $("#pause").click();
            break;
        case 34: // Page Down           		
            op = 1;            
            var page = cpage;
            page++;            
            $target.gotoPage(page);     
            break;
        case 8:  // Backspace
        case 33: // Page Up	            
            op = -1; 
            var page = cpage;
            page--;
            if (page != 0) {               
                $target.gotoPage(page); 
            }      
            break;
        case 27: // Escape
            op = 0;
            slideshowAction('close');
            break;
        case 83: // s   
//            alert('s'); 
            break;
        case 37: //Arrow left
            slideshowAction('prev');           
            break;
        case 39: //Arrow right
            slideshowAction('next');
            break;
    }
    if (op !== null) {
        if (e.preventDefault) e.preventDefault();
        else e.returnValue = false;
        if (op == -1) //Arrow left/up
        {
//            var btn = document.getElementById('a' + (cpage - 1));
//            if (btn != undefined) btn.onclick()
        }
        if (op == 0) //Escape/Enter
        {
            //alert('currentpage: 0 + ' + cpage); 
            //slideshowAction('close');
        }
        else if (op == 1) //Arrow right/down
        {
//            var btn = document.getElementById('a' + (cpage + 1));
//            if (btn != undefined) btn.onclick()
        }
        else  // space bar
        {
            // alert('keypress: else');
        }
    }
    return true;
}

function addEventListener(el, event, func) {
    try {        
        el.addEventListener(event, func, false);
    }
    catch (e) {
        try {
            el.detachEvent('on' + event, func);
            el.attachEvent('on' + event, func);
        }
        catch (e) {
            el['on' + event] = func;
        }
    }
}

function removeEventListener(el, event, func) {
    try {
        el.removeEventListener(event, func, false);
    }
    catch (e) {
        try {
            el.detachEvent('on' + event, func);
        }
        catch (e) {
            el['on' + event] = null;
        }
    }
}

// keycode reference
//case 8:  // Backspace
//case 13: // Enter        
//case 27: // Escape
//case 32: // Space
//case 33: // Page U		
//case 37: // Arrow left
//case 38: // Arrow up
//case 39: // Arrow right
//case 40: // Arrow down
//case 70: // f
//case 83: // s

/* HELPER FUNCTIONS */

function parse(data, prefix) {
    if (typeof prefix == 'undefined') prefix = '';
    try {
        $.each(data, function(key, val) {
            if (typeof val == 'function') // FUNCTION
                str += '\n' + prefix + key + ':  function()';
            else if (typeof val == 'string') // STRING
                str += '\n' + prefix + key + ':  "' + val + '"';
            else if (typeof val != 'object') // NUMBER or BOOLEAN
                str += '\n' + prefix + key + ':  ' + val;
            else if (isArray(val)) // ARRAY
                str += '\n' + prefix + key + ':  [ ' + val.toString() + ' ]'; // output delimited array
            else { // JSON
                if (recurseData === false || !hasKeys(val))
                    str += '\n' + prefix + key + ':  { }';
                else {
                    str += '\n' + prefix + key + ': {';
                    parse(val, prefix + '    '); // recurse another level deeper - indent output
                    str += '\n' + prefix + '}';
                }
            }
        });
    } catch (e) { }
    function isArray(o) {
        return (o && !(o.propertyIsEnumerable('length')) && typeof o === 'object' && typeof o.length === 'number');
    }
    function hasKeys(o) {
        var c = 0;
        for (k in o) c++;
        return c;
    }
}		
