﻿YAHOO.namespace("NA_Image"); // create new namespace

YAHOO.NA_Image.Sets = [];   // allow multiple configurations on screen
 
// find and return config set - create if not found
YAHOO.NA_Image.FindSet = function(setId) {

    var sets = YAHOO.NA_Image.Sets;
    for (i in sets) {
        if (sets[i].Id == setId) {
            return sets[i];   // found it
        }
    }
    return ( sets[sets.length] = new YAHOO.NA_Image.Config(setId) );    // not found create
}

YAHOO.NA_Image.AjaxObject = {

	handleSuccess:function(o){
		this.processResult(o);
	},

	handleFailure:function(o){
	    o.responseText = "<div>Sorry, No Data Found<div>";
		this.processResult(o);
	},

	processResult:function(o){
	    if (o.argument) {
            var div = document.createElement("div");
            div.innerHTML = o.responseText;
            
            var config = o.argument;
            if (config.Popup.Overlay) {
		        YAHOO.NA_Image.ShowContents(config, div);
		        YAHOO.NA_Image.SetCSS(config, div);
		    }
		}
	},

	startRequest:function(config, page) {
	
	   YAHOO.NA_Image.callback.argument = config;
	   var loc = location.href;
	   var root = location.protocol + "//" + location.host;
	   YAHOO.util.Connect.asyncRequest('GET', root + page, YAHOO.NA_Image.callback);
	}
};

YAHOO.NA_Image.callback = {

	success:YAHOO.NA_Image.AjaxObject.handleSuccess,
	failure:YAHOO.NA_Image.AjaxObject.handleFailure,
	scope: YAHOO.NA_Image.AjaxObject,
	cache:false
};

// for now - send ajax request using qs
YAHOO.NA_Image.UpdatePersona = function(group, page) {

    var config = YAHOO.NA_Image.FindSet(group);
    YAHOO.NA_Image.AjaxObject.startRequest(config, page);
    
    YAHOO.NA_Image.HidePop(group, config.Popup.popupId); // to close persona popup
}

YAHOO.NA_Image.ShowPopAjax = function(e, setId, imageEl, popupId, page) {

    var config = YAHOO.NA_Image.ShowPop(e, setId, imageEl, popupId, "", "", true);    
    YAHOO.NA_Image.AjaxObject.startRequest(config, page);
}

// show/hide popup window
YAHOO.NA_Image.ShowPop = function(e, setId, imageEl, popupId, title, root, ajax) {
        
    // find config for this popup 
    var config = YAHOO.NA_Image.FindSet(setId);
    var pop = config.Popup;  
    var dom   = YAHOO.util.Dom;
    var evt = YAHOO.util.Event;
    
    pop.imageEl = imageEl;
    pop.title = title;
    pop.root = root;
    pop.ajax = ajax;
    
    pop.mouseX = pop.mouseAnchorX = evt.getPageX(e);
    pop.mouseY = pop.mouseAnchorY = evt.getPageY(e);
    
    var toggle = popupId == pop.popupId;    // allow show/hide toggles
    YAHOO.NA_Image.HidePop(setId, pop.popupId);  // hide any possible existing first (only one allowed per set)
        
    if( popupId.length < 1 || toggle ) { return null; }
    
    pop.Overlay = new YAHOO.widget.Panel(setId, {visible:false, underlay:"shadow"} );
    pop.popupId = popupId;  
    
    if (config.OnDelayTime > 0) {
        pop.DelayPopup(config.OnDelayTime);
    }
    else {
        YAHOO.NA_Image.DisplayPop(config);
    }
    
    return config;  
}

YAHOO.NA_Image.DisplayPop = function(config) {

    if (!config) return;
    var pop = config.Popup;  
    var dom   = YAHOO.util.Dom;
    var evt = YAHOO.util.Event;

    var popupEl = dom.get(pop.popupId);
    YAHOO.NA_Image.LoadImage(config, popupEl, pop.root);  // parse popupEl and load image from servers image folder
           
    if (pop.title != null && pop.title.length > 0) { // use title/body/footer
        pop.Overlay.setHeader(pop.title);
    }
    
    var dataEl;
    if (pop.ajax) {
        dataEl = "<div style='padding:10px;'><img src='/images/wait.gif'> Please Wait...<div>";
    }
    else {
        dataEl = popupEl.cloneNode(true);
    } 
    YAHOO.NA_Image.ShowContents(config, dataEl);  
    
    var z =YAHOO.NA_Image.ShowPop.prototype.ZIndex(true); //allow multiple popups
    pop.Overlay.cfg.setProperty("zIndex",  z);
    pop.Overlay.render(document.body); // add as first child after body
      
    dom.setStyle(dataEl, "display", "block");
    pop.Recalc();    // get new regions  
    pop.isDisplayed = true;
        
    YAHOO.NA_Image.SetCSS(config, dataEl);       
               
    // add listener - so we can track cursor
    if (config.TrackMouse) {
        YAHOO.util.Event.addListener(pop.imageEl, "mousemove", pop.OnMouseMove, config);
    }
}

YAHOO.NA_Image.ShowContents = function(config, dataEl) {
    
    config.Popup.Overlay.setBody(dataEl);
    config.Popup.Recalc();  
 }
 
 YAHOO.NA_Image.SetCSS = function(config, dataEl) {
    
    var pop = config.Popup;  
    var dom   = YAHOO.util.Dom;
  
    var p = dom.get(config.Id);
    dom.addClass( p, config.PopupContainerClass );
             
    pop.SetPosition(); 

    var cb = dom.getElementsByClassName(config.CloseButtonClass, "div", dataEl);
    
    if (cb[0] != null) { 
        pop.closeBox = cb[0];
        YAHOO.util.Event.addListener(pop.closeBox, "click", pop.OnClose, config);
        dom.setStyle(pop.closeBox, "cursor", "pointer"); // change icons on cls box
    }             
}

YAHOO.NA_Image.ShowPop.prototype.ZIndex = function(inc) {

    if (!this.zIndex) {
        this.zIndex = 2000;
    }
    return (inc) ? this.zIndex++ : this.zIndex--; 
}

YAHOO.NA_Image.HidePop = function(setId, popupId) {

    var config = YAHOO.NA_Image.FindSet(setId);
    var pop = config.Popup;  
    var dom = YAHOO.util.Dom;
    
    if (pop.delay) {
        window.clearTimeout(pop.delay);
        pop.delay = null;
    }
    
    if (pop.Overlay) {
    
        //YAHOO.NA_Image.HilightImage(config, false); 
        
        if (config.TrackMouse) {
            YAHOO.util.Event.removeListener(pop.imageEl, "mousemove", pop.OnMouseMove);
        }
        if (pop.closeBox) {
            YAHOO.util.Event.removeListener(pop.closeBox, "click", pop.OnClose);
        }
    
        if (pop.isDisplayed == true) {
            YAHOO.NA_Image.ShowPop.prototype.ZIndex(false); 
        }
        pop.isDisplayed = false;
        pop.Overlay.hide();
        pop.Overlay.destroy();
        pop.Overlay = null;
    }
    
    pop.mouseDeltaX = 0;
    pop.mouseDeltaY = 0;
    pop.popupId = null; // hidden now
}

YAHOO.NA_Image.Log = function(txt) {
      
    var dom = YAHOO.util.Dom;
    var log = dom.get("debugLogger"); 
    if (log != null) {                   
        log.innerHTML = txt;
    }
}

// give some visual feedback that we are on the image
YAHOO.NA_Image.HilightImage = function(config, flag) {
    
    var pop = config.Popup;  
    var dom = YAHOO.util.Dom;
    
    if (flag) { // hilight
       // dom.setStyle(pop.curImageCntr, "border-color", "red");
        dom.setStyle(pop.imageEl, "opacity", ".3"); 
    }
    else { // de-highlight
      // dom.setStyle(pop.curImageCntr, "border-color", "white");
       dom.setStyle(pop.imageEl, "opacity", "1");
    }      
}

// loads image from media server using mangled guid/file name/ext from popup element
YAHOO.NA_Image.LoadImage = function (config, popupEl, root) {
    
    var pop = config.Popup;  
    var dom = YAHOO.util.Dom;
     
     if (config.ImagePath != null && popupEl != null) {   
         var aIdString = popupEl.id.toString();
         
         aIdString = "a_" + aIdString.substring(aIdString.indexOf("_")+1, aIdString.length); 
         var parentElem = dom.get(aIdString);
        if (parentElem)  { // only if requested
            var imgID = parentElem.id.toString();
            imgID = imgID.substring(imgID.indexOf("_") + 1,imgID.length);
            if ( document.getElementById("img_" + imgID) == null ) {
                var oImg = document.createElement("img");
                oImg.id = "img_" + imgID;
                parentElem.appendChild(oImg);
                var r = (root) ? root : config.ImagePath;
                imgID = imgID.substring(imgID.indexOf("_") + 1,imgID.length); // get true file name
                oImg.src = r + "/" + imgID;
            }
        }
    }
}

//
// each popup set (group) will need a config object
//
YAHOO.NA_Image.Config = function(setId) {

    var dom = YAHOO.util.Dom;
    
    this.Popup = new YAHOO.NA_Image.Popup(this);    // only one instance needed for each set
    this.Id    = setId; // allow multiple configurations
    
    // find div with setId (mangled) and split apart
    try {
    
        var MANGLE = "m23821989_";
        
        var data = dom.get(MANGLE+ setId).innerHTML;
        var args = YAHOO.lang.JSON.parse( dom.get('m23821989_' + setId).innerHTML );
        
        // container for one image (with chrome)
        this.HoverContainerClass    = ( "HoverContainerClass" in args) ? args.HoverContainerClass : "hoverItemContainer";
        
        this.BoundryClassTop        = ( "BoundryClassTop" in args)     ? args.BoundryClassTop : null;
        this.BoundryClassRight      = ( "BoundryClassRight" in args)   ? args.BoundryClassRight : null;
        this.BoundryClassBottom     = ( "BoundryClassBottom" in args)  ? args.BoundryClassBottom : null;
        this.BoundryClassLeft       = ( "BoundryClassLeft" in args)    ? args.BoundryClassLeft : null;
        
        this.BoundryClass           = ( "BoundryClass" in args)     ? args.BoundryClass : null;
        this.CloseButtonClass       = ( "CloseButtonClass" in args) ? args.CloseButtonClass : "_closeButtonClass";
        this.OnDelayTime            = ( "OnDelayTime" in args)      ? args.OnDelayTime : "";
        this.Padding                = ( "Padding" in args)          ? args.Padding : "";
        this.VisualPointer          = ( "VisualPointer" in args)    ? args.VisualPointer : "";
        this.Shadow                 = ( "Shadow" in args)           ? args.Shadow : "";
        this.TrackMouse             = ( "TrackMouse" in args)       ? args.TrackMouse : "";
         
        this.PopupContainerClass    = ( "PopupContainerClass" in args) ? args.PopupContainerClass : "_popupContainer"; 
        this.ImagePath              = ( "ImagePath" in args) ? args.ImagePath : null;
        
        // allows each edge of gallery edge to be used/ignored
        this.GalleryConstraint_L    = ( "ConstrainLeft" in args) ? args.ConstrainLeft : false;  
        this.GalleryConstraint_T    = ( "ConstrainTop" in args)  ? args.ConstrainTop : false;
        this.GalleryConstraint_R    = ( "ConstrainRight" in args) ? args.ConstrainRight : false; 
        this.GalleryConstraint_B    = ( "ConstrainBottom" in args) ? args.ConstrainBottom : false; 
        
        this.PopupSize              = [200,200];  
        if ( "XSize" in args) this.PopupSize[0] = args.XSize;
        if ( "YSize" in args) this.PopupSize[1] = args.YSize;
        
        this.HighlightImageSelection = true; 
        this.UseIFrame               = true; // add iframe under popup to hide ie 6 select tags
    }
    catch (e) {
        alert("Invalid popup configuration data (JSON)");
    }
}

//
// Popup class - handles image, imageBox, and viewport regions, calc best fit
//
YAHOO.NA_Image.Popup = function (config) {
    
     this.config       = config; // attach config object
   
    // regions
    this.imageBoxRgn  = null;
    this.imageRgn     = null;
    this.clientRgn    = null;
    
    // single constraint container or individ surrounding
    this.containerRgn = null;
    this.containerTRgn = null;
    this.containerRRgn = null;
    this.containerBRgn = null;
    this.containerLRgn = null;
    
    this.popupRgn     = null;
    
    this.curImageCntr  = null;        // image container el of any pending show
    this.closeBox      = null;
    this.imageEl       = null;
    this.popupId       = null;
    this.delay = null;
    
    this.isDisplayed   = false;
    this.count         = 0;
    this.mouseAnchorX  = 0;
    this.mouseAnchorY  = 0;
    this.mouseX   = 0;
    this.mouseY   = 0;
    
    this.Overlay       = null;
}

YAHOO.NA_Image.Popup.prototype.DelayPopup = function (time) {
    
    thisObj = this;
    this.delay = setTimeout(function() { thisObj.OnDelayPopup.call(thisObj); }, time);    
}

YAHOO.NA_Image.Popup.prototype.OnDelayPopup = function () {
   
   YAHOO.NA_Image.DisplayPop(this.config);
}

// calculate the regions of the image, imagebox, and current visible viewport area
YAHOO.NA_Image.Popup.prototype.Recalc = function () {
   
    var dom = YAHOO.util.Dom;
    
    this.popupRgn     = dom.getRegion(this.config.Id); // get popup region
    
    this.imageRgn     = dom.getRegion(this.imageEl); //image
    this.clientRgn    = dom.getClientRegion();
    
    var bounds;
    // get optional boundry elements
    if (this.config.BoundryClass) {
        bounds = dom.getAncestorByClassName(this.imageEl, this.config.BoundryClass);
        this.containerRgn = (bounds != null) ? YAHOO.util.Dom.getRegion(bounds) : null;  
    }
        
    if (this.config.BoundryClassTop) {
        bounds = dom.getElementsByClassName(this.config.BoundryClassTop, "div");
        this.containerTRgn = (bounds[0] != null) ? YAHOO.util.Dom.getRegion(bounds[0]) : null; 
    }
    
    if (this.config.BoundryClassRight) {
        bounds = dom.getElementsByClassName(this.config.BoundryClassRight, "div");
        this.containerRRgn = (bounds[0] != null) ? YAHOO.util.Dom.getRegion(bounds[0]) : null; 
    }
    
    if (this.config.BoundryClassBottom) {
        bounds = dom.getElementsByClassName(this.config.BoundryClassBottom, "div");
        this.containerBRgn = (bounds[0] != null) ? YAHOO.util.Dom.getRegion(bounds[0]) : null; 
    }
   
    if (this.config.BoundryClassLeft) {
        bounds = dom.getElementsByClassName(this.config.BoundryClassLeft, "div");
        this.containerLRgn = (bounds[0] != null) ? YAHOO.util.Dom.getRegion(bounds[0]) : null; 
    }
        
    if (  dom.hasClass(this.imageEl, this.config.HoverContainerClass) ) {
        this.curImageCntr = this.imageEl; // container is same as hoverEl
    }
    else { // try to find parent container
        this.curImageCntr = dom.getAncestorByClassName(this.imageEl, this.config.HoverContainerClass);
    }
        
    if (this.curImageCntr != null) {
        this.imageBoxRgn = dom.getRegion(this.curImageCntr);   
    }
    else { 
        alert("No hover container found: set 'HoverContainerId' in config control"); // warn developer
        this.imageBoxRgn = new YAHOO.util.Region(0,0,0,0); 
    }
}

// Properties for regions
YAHOO.NA_Image.Popup.prototype.GetImageRgn = function () {
    return this.imageRgn;
}
YAHOO.NA_Image.Popup.prototype.GetImageBoxRgn = function () {
   
    var CURSIZE = 20;
    var p = this.config.Padding;
    // YAHOO.util.Region ( t , r , b , l ) 
    var rgn;
    
    if (this.config.TrackMouse) {
        
        // make region size of cursor and let it track mouse
        var x = this.mouseX;
        var y = this.mouseY;
        rgn = new YAHOO.util.Region ( y-CURSIZE, x+p+CURSIZE, y+CURSIZE, x-p-CURSIZE ); 
    }
    else {                           
        rgn = new YAHOO.util.Region ( this.imageBoxRgn.top,    this.imageBoxRgn.right+p, 
                                          this.imageBoxRgn.bottom, this.imageBoxRgn.left-p ); 
    }   
    return rgn;
}

// include any optional constraint bounds
// allow both single container or multiple containers
YAHOO.NA_Image.Popup.prototype.GetClientRgn = function () {
    
    var ct = this.clientRgn.top;
    var cr = this.clientRgn.right;
    var cb = this.clientRgn.bottom;
    var cl = this.clientRgn.left;

    if (this.containerRgn) { // use single container as constraint

        if (this.config.GalleryConstraint_T) ct = this.containerRgn.top;
        if (this.config.GalleryConstraint_L) cl = this.containerRgn.left;
        if (this.config.GalleryConstraint_R) cr = this.containerRgn.right;
        if (this.config.GalleryConstraint_B) cb = this.containerRgn.bottom;
    }
    if (this.containerTRgn) ct = this.containerTRgn.bottom;
    if (this.containerRRgn) cr = this.containerRRgn.left;
    if (this.containerBRgn) cb = this.containerBRgn.top;
    if (this.containerLRgn) cl = this.containerLRgn.right;
        
    
    var t = Math.max(this.clientRgn.top,    ct);
    var l = Math.max(this.clientRgn.left,   cl);
    var r = Math.min(this.clientRgn.right,  cr);
    var b = Math.min(this.clientRgn.bottom, cb);
    
    return ( new YAHOO.util.Region (t, r, b, l) );
}

YAHOO.NA_Image.Popup.prototype.GetGalleryContainerRgn = function () {
    return this.containerRgn;
}

// find area for popup that fits within client area (current scrolled viewport)
// and outside of clicked image box (if possible)
// otherwise just draw best partial fit.
// returns [x,y] position of fit
YAHOO.NA_Image.Popup.prototype.FindBestPosition = function () {

   // image and client regions
    var iRgn = this.GetImageBoxRgn(); // shortcuts
    var cRgn = this.GetClientRgn();
    
    var popWidth = this.popupRgn.right - this.popupRgn.left;
        
    var x = iRgn.left;
    var y = iRgn.top;
    
    // check if will fit in each edge zone (t,b,l,r)
    var lEdgeOk = (iRgn.left  - cRgn.left    ) >= popWidth;
    var rEdgeOk = (cRgn.right - iRgn.right   ) >= popWidth;
   
    // ok, now we are ready to fit
    if (rEdgeOk) {
        x +=(iRgn.right - iRgn.left);         
        y = this.adjustVert(y, cRgn); // keep on screen if possible
    }
    else if (lEdgeOk) {
        x -= popWidth;   
        y = this.adjustVert(y, cRgn); // keep on screen if possible
    }
    else {  // wont fit - just hang to the right
        x +=(iRgn.right - iRgn.left);         
    }        
    return [x,y];
}

// if popup is clipping then attempt to adjust it
YAHOO.NA_Image.Popup.prototype.adjustVert = function (y, cRgn) {

   // return y;
   var popHeight = this.popupRgn.bottom - this.popupRgn.top;

    var vertFitOk = (cRgn.bottom - cRgn.top  ) >= popHeight;
    
    if (vertFitOk) {    // only adj if there is room to
        if (y < cRgn.top) { 
            y += (cRgn.top-y+2);
        }
        else if ( (y + popHeight) > cRgn.bottom) { // move up
            //var adj = (YAHOO.env.ua.ie == 6) ? 50 : 2; 
            var adj = 2;
            y -= ( (y + popHeight) - cRgn.bottom) + adj;
        }
    } 
    else { // move up as high as we can
        y += (cRgn.top-y+2);
    }
    return y;
} 

// get best fit and set popup x,y 
YAHOO.NA_Image.Popup.prototype.SetPosition = function() {

    if (this.Overlay) {
        var pos = this.FindBestPosition();
        this.Overlay.cfg.setProperty("xy", [ pos[0], pos[1] ]);
        this.Overlay.show();
    }
}

YAHOO.NA_Image.Popup.prototype.OnClose = function(e, config) {

    YAHOO.NA_Image.HidePop(config.Id, config.Popup.popupId);
}

YAHOO.NA_Image.Popup.prototype.OnMouseMove = function(e, config) {
      
    var pop = config.Popup;
    var dom = YAHOO.util.Dom;
    var evt = YAHOO.util.Event;
       
    pop.mouseX = evt.getPageX(e);
    pop.mouseY = evt.getPageY(e);
    pop.SetPosition();
    
    //var txt = xp + " " + yp;
    //YAHOO.NA_Image.Log(txt);
}

// end of popup class




