/* $Id: mediaPanel.js 31159 2010-05-03 04:52:03Z twilson $ */
var aTag,aHref,aTitle,mContainer,mWidth,mHeight,mClickOffArea,caroselCollection,objIdStr,ajaxCall,mTitle;
var objHeight,objWidth;

var mediaPanelController = {

    init : function(){
    
		if (window.jQuery)
		{
		    var photos = jQuery("a[rel^='prettyOverlay'],a[rel^='prettyPhoto']");
		    photos.unbind();
		    
	        if (photos.prettyPhoto)		    
		    {
                // setup jQuery lightbox
                photos.prettyPhoto
                ({
                    animationSpeed: 'normal', /* fast/slow/normal */    
                    padding: 40, /* padding for each side of the picture */
                    opacity: 0.50, /* Value betwee 0 and 1 */
                    showTitle: false, /* true/false */
                    allowresize: true /* true/false */
                }); 
            }
		}
		 
        mPanel = jQuery("#mediaPanel");
        mContainer = jQuery("#mContent");
        mClickOffArea = jQuery('#contentArea');
        mTitle = document.title;
        
        //attach hooks to media links	
        var mediaLinks = jQuery('a.media,area.media');

		//do the links already have this event?
		
	    mediaLinks.unbind('click', this.addClick);
	    mediaLinks.bind('click', this.addClick);
		
	    //check the hash for urls
	    if(window.location.hash)
	    {
        var returnURL;
        var foundIndex = -1;
        var paramBits;

            var url = window.location.hash.split('#')[0];
	        //var hashUrl = window.location.hash.split('#')[1];
            var hashUrl = (''+window.location).split('#')[1];
	        if(hashUrl != null && hashUrl.length>0)
	        {
	            hashUrl = hashUrl.replace("[","%5B").replace("]","%5D");
	            hashUrl = hashUrl.replace(new RegExp(" ", "g"), "%20").toLowerCase();
	            
	            mediaLinks.each(function(i) {
	                if (media.fixpath(this.href).split('?')[0] == hashUrl.split('?')[0])
	                {
	                    if (this.title) aTitle = this.title;
	                    aTag = jQuery(this);
	                }
	            });

                // Remove query string params from the URL
                if (hashUrl.lastIndexOf('?') != -1)
                {
                    // there is a query string in the href passed in, check if it manually defines returnURL
                    paramBits = hashUrl.substring(hashUrl.lastIndexOf('?') + 1).split('&');
                    
                    for (i in paramBits)
                    {
                        var paramAndValue = paramBits[i].split('=');
                        if (paramAndValue[0].toLowerCase() == 'returnurl')
                        {
                            // this is a param defining returnURL
                            returnURL = 'returnURL=' + paramAndValue[1];
                            foundIndex = i;
                            break;
                        }
                    }
                    
                    if (foundIndex != -1)
                    {
                        // remove returnURL from hashUrl, since we'll pass it in media.load() below
                        paramBits.splice(foundIndex, 1);
                    }
                    
                    // build the url, minus the returnURL param
                    hashUrl = hashUrl.substring(0, hashUrl.lastIndexOf('?') + 1) + paramBits.join('&');
                    
               }
                	            
				if(aTag) {
				    if (aTag.hasClass('secure'))
				    {
				        // this media element has stated that it needs to be loaded over SSL
                        var newHref;
                        if (window.location.href.indexOf('https') < 0)
                        {
                            if (window.location.href.indexOf('RequiresSecure') < 0)
                            {
                                if (url.indexOf('?') < 0)
                                {
                                    window.location = url.replace('http://', 'https://') + '?RequiresSecure=1' + '#' + hashUrl;
                                }
                                else
                                {
                                    window.location  = url.replace('http://', 'https://') + '&RequiresSecure=1' + '#' + hashUrl;
                                }
                            }
                            else
                            {
                                window.location = window.location.href.replace('http://', 'https://');
                            }
                        }
                        else
                        {
                            try{media.load(hashUrl, returnURL);}catch(e){/*alert(e.number + ': ' + e.description );*/}
                        }
				    }
				    else
				    {
                        try{media.load(hashUrl, returnURL);}catch(e){/*alert(e.number + ': ' + e.description );*/}
	                }
	            }

				// now loop again, to find anything needing auto-loading :(
				// the main intended use for this is flash using swfaddress
				if (window.location.hash.split('flashhistory')[1] != null) 
				{
				    mediaLinks.each(function() {
				        aTag = jQuery(this);
				        if (aTag.is('.auto'))
				        {
						    media.load(media.fixpath(this.href));
						}
				    });
				}
	        }
	    }
    },

	addClick : function(e){
	    if (e.preventDefault)
            e.preventDefault();
        aTag = jQuery(this);
        aTitle = aTag.attr('title');
        aHref = media.fixpath(aTag.attr('href'));
        var returnURL;
        var foundIndex = -1;
        var paramBits;

        if (aHref.lastIndexOf('?') != -1)
        {
            // there is a query string in the href passed in, check if it manually defines returnURL
            paramBits = aHref.substring(aHref.lastIndexOf('?') + 1).split('&');
            
            for (i in paramBits)
            {
                var paramAndValue = paramBits[i].split('=');
                if (paramAndValue[0].toLowerCase() == 'returnurl')
                {
                    // this is a param defining returnURL
                    returnURL = 'returnURL=' + paramAndValue[1];
                    foundIndex = i;
                    break;
                }
            }

        }
        
        var isSecure = aTag.hasClass('secure');
        var inHttps = window.location.href.indexOf('https') >= 0;
        
        if (isSecure)
        {
            // this media element has stated that it needs to be loaded over SSL
            var newHref;
            if (!inHttps)
            {
                var url = window.location.href.split('#')[0];
                
                if (paramBits)
                    aHref = aHref.substring(0, aHref.lastIndexOf('?') + 1) + paramBits.join('&');

                if (url.lastIndexOf('?') < 0) {
                    url = url.replace('http://', 'https://') + '?RequiresSecure=1#' + aHref;
                }
                else {
                    url = url.replace('http://', 'https://') + '&RequiresSecure=1#' + aHref;
                }
                window.location = url;
                
                this.href = 'javascript:void(0);';
            }
            else
            {
                if (foundIndex != -1)
                {
                    // remove returnURL from aHref, since we'll pass it in media.load() below
                    paramBits.splice(foundIndex, 1);
                }
                // build the url, minus the returnURL param
                if (paramBits)
                    aHref = aHref.substring(0, aHref.lastIndexOf('?') + 1) + paramBits.join('&');

                try{media.load(aHref, returnURL);}catch(e){/*alert(e.number + ': ' + e.description );*/}
                //this.href = 'javascript:void(0);';
                
                //update address bar with hash, unless a swf/inline or has hash already
                if (! ( (getFileExtension(aHref)=="swf") || (aTag.hasClass('inline')) || (window.location.hash && window.location.hash.length > 0) ) ){
    			    location.href = '#' + aHref;
		        }
            }
        }
        else if (aTag.attr('rel') == null || aTag.attr('rel') == '')
        {
            try{media.load(aHref, returnURL);}catch(e){/*alert(e.number + ': ' + e.description );*/}

            //sometimes the link will still action, so try and change it before it does
            //this.href = 'javascript:void(0);';

            //update address bar with hash, unless a swf/inline or has hash already
            if (    !((getFileExtension(aHref)=="swf") || aTag.is('.inline') || (window.location.hash && window.location.hash.length > 1) ) ){
			    location.href = '#' + aHref;
		    }
		}
		else
		{
		    //This link has a 'rel' attribute, so we need to perform an ajax call for it

		    //sometimes the link will still action, so try and change it before it does
            //this.href = 'javascript:void(0);';
            
            //Look for the id of the element to replace the html into. Should be in the rel attribute
            objIdStr = aTag.attr('rel');

            //Show the loading spinner
            jQuery("#" + objIdStr).html("<div style='position:absolute; z-index:999; background-color:#F6F6F6; margin:20px;'><img src='/global/images/spinner_grey.gif' />&nbsp;Loading...</div>" + jQuery("#" + objIdStr).html());
            
            //alert(aHref + ", " + objIdStr);
            try{media.loadReplace(aHref);}catch(e){/*alert(e.number + ': ' + e.description );*/}
            
            jQuery("a[rel], a[class*=on]").removeClass("on");
            
            aTag.addClass('on');
		}
		
        return false;
		
	},
	
    load : function(strUrl, strPost){
    
        //remove clickoff area
        mClickOffArea.unbind('click');
	    //try{$E.removeListener(mClickOffArea, "click", hider);}catch(e){}
	    
        if(!strPost)
        {
            // nothing was passed in as the post string, so we know we need to manually set the returnURL param
			strPost="isAjax=1&returnURL=" + location.href;
        }
		else
        {
            // the only thing that gets passed in (if anything) is returnURL, so only set the isAjax flag
		    strPost+="&isAjax=1";
        }
        
	//	strPost+="&randy=" + Math.random()+"";
		
		//alert(strPost);
		    
		//strPost+="&returnURL=" + location.href;

		
        // is inline ?
        if (aTag.is('.inline')) {

        //get size of inner contents

	        mContainer = jQuery(aTag.children().get()[0]);
	        
	        if(mContainer.length == 0)return false;

	        mHeight = mContainer.height();
	        mWidth  = mContainer.width();

			objHeight = mHeight;
			objWidth  = mWidth;
	        
            var newDiv = document.createElement("div");
            aTag.replaceWith(newDiv);
            
            mContainer = jQuery(newDiv);
            
            mContainer.height(mHeight);
            mContainer.width(mWidth);
            mContainer.css("overflow", "hidden");
            
            media.spin();      
        }else{
      
      			objHeight = "";
      			objWidth  = "";

            media.show();
            media.spin();
            media.fixPosition();
        }
            
            
        //MEDIA SWITCH
        var ext = getFileExtension(strUrl);
  
        switch(ext){
            //IMAGE OR MOVIE
            case "jpg": case "gif": case "png": case "flv": case "swf":
            
                strPost += "&ext=" + ext + "&file=" + strUrl + "&h=" + objHeight + "&w=" + objWidth;
                if(aTitle)
                    strPost += "&title=" + aTitle;
                if(aTag.is('.inline'))
                    strPost += "&inline=1";
                
                //AM I PART OF A GALLERY? - CREATE IMAGE OBJECT ARRAY
                // a -> li -> ul (with gallery className)
	   			if(aTag){
	   			    var galleryTag = aTag.parent('*').parent('.gallery');
	   			    
	   			    if (galleryTag.length > 0)
	   			    {
	   			        caroselCollection = galleryTag('a.media');
	   			        strPost += "&carousel=1";
	   			    }
				}
				
                strUrl = "/global/templates/mediaTemplate.aspx";
                break
                
			case "aspx":
				strPost += "&file=" + URLEncode(strUrl);
                strUrl = "/global/templates/codeTemplate.aspx";
				break
            default: ///
                if (aTag.is('.inline') && aTag.is('[href^=/media]'))
                {
                    strPost += "&ext=" + ext + "&file=" + strUrl + "&h=" + objHeight + "&w=" + objWidth;
                    if(aTitle)
                        strPost += "&title=" + aTitle;
                    if(aTag.is('.inline'))
                        strPost += "&inline=1";
                    
                    //AM I PART OF A GALLERY? - CREATE IMAGE OBJECT ARRAY
                    // a -> li -> ul (with gallery className)
	   			    if(aTag){
	   			        var galleryTag = aTag.parent('*').parent('.gallery');
    	   			    
	   			        if (galleryTag.length > 0)
	   			        {
	   			            caroselCollection = galleryTag('a.media');
	   			            strPost += "&carousel=1";
	   			        }
				    }
    				
                    strUrl = "/global/templates/mediaTemplate.aspx";
                }
                break;
        }
        
		//LOAD MEDIA CONTENT
		ajaxCall = jQuery.ajax({
		    type: "POST",
		    url: strUrl,
		    data: strPost,
		    a: aTag,
		    success: function(o){
		      var thisRef = this.a;
		      setTimeout(function(){media.draw(o, thisRef)}, 2000);
		    },
		    failure: media.fail
		});
    },
    
    loadReplace : function(strUrl, elementId){
        if(elementId)objIdStr = elementId;
    
	    jQuery.ajax({
	        type: "GET",
	        url: strUrl,
            success : function(o){
                media.drawReplace(o);
                try{
                    //if(aHref) aTag.attr('href', aHref);
                }catch(e)
                {}
            },
            failure : function(msg){media.failReplace(msg);try{if(aHref)aTag.attr('href',aHref);}catch(e){}}
	    });
    },

    show: function(){
		window.scroll(0, 0);
		mPanel.css('display', 'block');
		
	//	mPanel.css('position', 'fixed');
        
        //IE 6
        //position: absolute;
        //top: expression((document.documentElement.scrollTop || document.body.scrollTop) + Math.round(17 * (document.documentElement.offsetHeight || document.body.clientHeight) / 100) + 'px');


        
        
        document.title = mTitle;	    

    },
    
    hide : function(a){
        mPanel.css('top', '-500');
        mPanel.css('display', 'none');

		// swfaddress uses the hash, so dont clobber it unless the conents of window.location after the hash
		// is the same as the href of the media link we clicked
		if(window.location.hash){
		    var tempHref = "";

			if(a.attr('href').split(window.location.protocol)[1] != null){
			    // protocol was included in the aTag href
			    tempHref = window.location.protocol + "//" + window.location.host + window.location.port + window.location.href.split("#")[1];
			} else {
			    // href had no protocol
			    tempHref = window.location.href.split("#")[1];
			}
			
            tempHref = tempHref.replace("[","%5B").replace("]","%5D");
            tempHref = tempHref.replace(new RegExp(" ", "g"), "%20").toLowerCase();

			if(media.fixpath(a.attr('href')) != tempHref.toLowerCase()) {
        		this.href = location.href;
        	} else {
				top.location.href=location.href.replace( /(.*)#.*/, "$1")+"#";
			}
		}
		
		jQuery("#mContent").html("");
		
        mPanel = jQuery("#mediaPanel");
        mContainer = jQuery("#mContent");
		
	    //REMOVE LISTENER CLICK CONTENT AREA?
	    mClickOffArea.unbind('click');


        document.title = mTitle;	    
	    
    },

    draw : function(o, a){
        
       // jQuery("#serviceHeader").html(o);
         
        mContainer = mContainer.html(o);
        
        //mContainer = replaceHtml(mContainer.get(0), o);
        
        //run anything in the script tags
        try {
            //Execute any scripts in the response text
            var scriptTags = jQuery("mContent script").each(function() {
                if (this.innerHTML != null){
                    eval(this.innerHTML);
                }
            });
            
            //Set any hidden objects to visible in the response text
            var objectTags = jQuery("#mContent object").each(function() {
                if (this.css('visibility') == 'hidden'){
                    this.css('visibility') = 'visible';
                }
            });
            //eval(xmlNodeText(o,"script"));
			
            
            /*var script = document.createElement('script');alert(o.responseText.getElementsByTagName('script').length);
			var scriptText = document.createTextNode(xmlNodeText(o.responseText, "script"));
			script.type = 'text/javascript';
			script.language = 'javascript';alert(scriptText.data);
			script.text = scriptText.data.trim();
			mContainer.appendChild(script);*/
        } catch(e) {    
            //alert(e.number + ': ' + e.description + ': ' + o.responseText );
          //  media.fail("Error in file.");
        }
        
        if (!a.is('.inline'))
        {
            mClickOffArea.click(function() { media.hide(a); });
            jQuery("#mediaCloseButton").click(function() { media.hide(a); });

            media.fixPosition();
            media.show();
        }else{
        
            //alert("inline");
        }
        
        mContainer = jQuery("#mContent");
    },
    
    drawReplace : function(o){
        
        jQuery("#" + objIdStr).html(o);
        //KK. After replace call init, if there is something which need to be init on dynamic content
       // alert("why dont you work");
        media.init();
    },
		
	fail : function(msg){
	    mContainer.html("<b>Load failed</b><p>Please try again.</p><br>");
	},
	
	failReplace : function(msg){
	    jQuery("#" + objIdStr).html("<b>Load failed</b><p>Please try again.</p><br>");
    },

    spin : function(){
        mContainer.html("<img src='/global/images/spinner_grey.gif' class='spinner' align='absmiddle'>");
    },
    
    fixpath: function(u){
        regx = new RegExp(window.location.protocol + "\/\/" + window.location.host );
        
        //return u.replace(regx,"").toLowerCase();

        var url = u.replace(regx,"");
        url = url.replace("[","%5B").replace("]","%5D");
        return url.replace(new RegExp(" ", "g"), "%20").toLowerCase();
    },
    
    fixPosition: function(){

        //SIZE + POSITION
        mWidth = mContainer.width() + 30;
        mHeight = mPanel.height();

        mPanel.width(mWidth);
        
        cWidth = jQuery(window).width();
        cHeight = window.innerHeight
        || document.documentElement && document.documentElement.clientHeight
        || document.body.clientHeight;

        newWidth = (cWidth/2)-(mWidth/2);
        newWidth = (newWidth < 0) ? 0 : newWidth;
        newHeight = (cHeight/2)-(mHeight/2);
        newHeight = (newHeight < 0) ? 0 : newHeight;

        mPanel.css('left', newWidth + "px");
        mPanel.css('top', (newHeight+50) + "px");
    }

}

if (typeof media != "undefined") {
    for (prop in mediaPanelController) {
        if (typeof mediaPanelController[prop] == "function") {
            media[prop] = mediaPanelController[prop];
        }
    }
}
else {
    media = mediaPanelController;
}

window.onresize = function(){
    media.fixPosition();
}


