/*
 * Custom OH modules
 * requires YUI Loader
 */
// Global (site-wide) variables
var OH    = YAHOO.namespace('OH');
Event = YAHOO.util.Event;
DOM   = YAHOO.util.Dom;
	
// define / add our custom modules
(function () {
	OH.Application = {};
	OH.Application.onInit = new YAHOO.util.CustomEvent("onInit");
	OH.Application.onLoad = new YAHOO.util.CustomEvent("onLoad");
	OH.Application.onDispatcherLoad = new YAHOO.util.CustomEvent("onDispatcherLoad");
	OH.Application.lazyLoadImages = new YAHOO.util.CustomEvent("lazyLoadImages");
	OH.Application.scrollTabLoadedShow = new YAHOO.util.CustomEvent("scrollTabLoadedShow");
	branchesLoaded = [];
	
    var aModules = [{
            name: 'OH.util',
            type: 'js',
            fullpath: '/s/OH.util.js',
            requires: ['event', 'dom', 'connection'],
            optional: []
        }, {
            name: 'OH.DDList',
            type: 'js',
            fullpath: '/s/OH.DDList.js',
            requires: ['dom', 'dragdrop', 'animation'],
            optional: []
        }, {
            name: 'OH.FormValidator',
            type: 'js',
            fullpath: '/s/OH.form_validation.js',
            requires: ['OH.util', 'dom', 'event'],
            optional: []
        }, {
            name: 'OH.Selector',
            type: 'js',
            fullpath: '/s/OH.Selector.js',
            requires: [],
            optional: []
        }, {
            name: 'OH.ContentBin',	
            type: 'js',
            fullpath: '/s/OH.ContentBin.js',
            requires: ['OH.util', 'OH.Selector', 'container', 'connection', 'json', 'datasource', 'paginator'],
            optional: ['slider']
        }, {
			name: 'OH.TabView',
			type: 'js',
			fullpath: '/s/OH.TabView.js',
			requires: ['OH.util', 'Dispatcher', 'connection', 'dom', 'element', 'event', 'tabview'],
			optional: []
		}, {
			name: 'OH.SelectViews',
			type: 'js',
			fullpath: '/s/OH.SelectViews.js',
			requires: ['OH.util'],
			optional: []
		}, {
			name: 'OH.SlidingPanel',
			type: 'js',
			fullpath: '/s/OH.SlidingPanel.js',
			requires: ['OH.util', 'animation'],
			optional: []
		}, {
			name: 'OH.InlineEdit',
			type: 'js',
			fullpath: '/s/OH.inlineEdit.js',
			requires: ['OH.util'],
			optional: []
		}, {
			name: 'OH.Curtains',
			type: 'js',
			fullpath: '/s/OH.Curtains.js',
			requires: ['OH.util'],
			optional: []
		},{
			name: 'SwfObject',
			type: 'js',
			fullpath: '/s/mediaplayer/swfobject.js',
			requires: ['OH.util'],
			optional: []
		}, {
			name: 'Dispatcher',
			type: 'js',
			fullpath: '/s/dispatcher-min.js',
			requires: ['OH.util', 'dom', 'event', 'connection'],
			optional: []
		}, {
			name: 'OH.Connections',
			type: 'js',
			fullpath: '/s/OH.Connections.js',
			requires: ['OH.util'],
			optional: []
		}, {
			name: 'loadswf',
			type: 'js',
			fullpath: '/s/loadswf.js',
			requires: ['OH.util', 'SwfObject'],
			optional: []
		}, {
			name: 'OH_Forms',
			type: 'js',
			fullpath: '/s/OH.Forms.js',
			requires: ['OH.util', 'OH.Selector'],
			optional: []
		}, {
			name: 'ScrollTabView',
			type: 'js',
			fullpath: '/s/ScrollTabView.js',
			requires: ['tabview'],
			optional: []
		}, {
			name: 'EventsListing',
			type: 'js',
			fullpath: '/s/events.js',
			requires: ['OH.Selector'],
			optional: []
		}, {
			name: 'YQLAutoTagger',
			type: 'js',
			fullpath: '/s/YQLAutoTagger.js',
			requires: ['OH.Selector'],
			optional: []
		}, {
			name: 'EditHistree',
			type: 'js',
			fullpath: '/s/EditHistree.js',
			requires: [],
			optional: []
		}, {
			name: 'fbConnect',
			type: 'js',
			fullpath: 'http://static.ak.connect.facebook.com/connect.php/en_US',
			requires: [],
			optional: []
		}
    ];


	function YUILoadComplete() {
		//var myLogReader = new YAHOO.widget.LogReader(); 
		//YAHOO.log("YUILoadComplete");
		
		OH.loader = new YAHOO.util.YUILoader(); //for reuse in other pages
		
		for (var i=0; i < aModules.length; i++){
			OH.loader.addModule(aModules[i]);
		}
		
		
		OH.modals = {};
  
		/* OH.MODAL2 */
		OH.Modal2 = function (config) {
			DetectLanguage();
			config = config || {};
			var defaults = {
				base: OH.StaticHost,
				buttons: [],
				fixedcenter: true,
				visible: false,
				close: true,
				draggable: false,
				modal: true,
				constraintoviewport: true,
				iframe: false,
				zIndex: 999
			};
		 config = YAHOO.lang.merge(defaults, config);
		 var url = config.url,
		  id = config.id || (url ? url.replace(/\W+/g, '_') : YAHOO.util.Dom.generateId()),
		  modal,
		  cached_modal;
		  //iframe;
		 
		if (!config.width) {
			config.width = "850px";
		}
		if (!config.height) {
			config.height = "600px";
		}
		if (OH.modals[id]) {
			modal = cached_modal = OH.modals[id];
		} 
		else {
			modal = new YAHOO.widget.Dialog(id, config);
		}
		 
		if (url) {
			if (url.indexOf('aslightbox') === -1){
				url += (url.indexOf('?') === -1 ? '?aslightbox=1' : '&aslightbox=1'); 
			}
			
			var translationElement = DOM.get('translationRef');
			
			if(translationElement){
				var translationRef = translationElement.href;
				var langRef = translationRef.split('#')[1];
				if (typeof(langRef) !== "undefined"){
					url += "#"+langRef;
				}
			}
		}
		 
		modal.beforeRenderEvent.subscribe(function (){
			this.element.style.position = 'absolute';
			YAHOO.util.Dom.addClass(modal.innerElement, 'oh-lightbox');
		});
		
		modal.showEvent.subscribe(function () {
			OH.modal = modal;
			YAHOO.util.Dom.addClass(modal.element, "modal");
			YAHOO.util.Dom.setStyle(modal.element, 'z-index', config.zIndex);
			YAHOO.util.Dom.setStyle(modal.mask, 'z-index', config.zIndex - 1);
		});
				 
		modal.hideEvent.subscribe(function (e) {
			this.setBody('');
		});
		
		modal.closeEvent = new YAHOO.util.CustomEvent("closeEvent", this); 
		 
		modal.setBody('');
		var fetcher = YAHOO.plugin.Dispatcher.fetch ( modal.body, url, {onLoad: function(){
			pageTracker._trackPageview(url);
			OH.Application.onDispatcherLoad.fire(); 
			transCount = 0;
			translateOHPage(OH.Selector('h1, h2, h3, label, span, a, p:not(.action), div.histree-name', modal.element));
			transCount = 0;
		}} );
		
		modal.render(document.body);
		 
			OH.modals[modal.id] = modal;
			return OH.modals[modal.id];
		} // OH.Modal2
		
		/* OH.MODAL */
		OH.Modal = function (config) {
			config = config || {};
			var defaults = {
					base: OH.StaticHost,
					buttons: [],
					fixedcenter: true,
					visible: false,
					close: true,
					draggable: false,
					modal: true,
					constraintoviewport: true,
					iframe: true,
					zIndex: 999
				};
			config = YAHOO.lang.merge(defaults, config);
			var url = config.url,
				id = config.id || (url ? url.replace(/\W+/g, '_') : YAHOO.util.Dom.generateId()),
				modal,
				cached_modal,
				iframe;
			
			if (!config.width) {
				config.width = "850px";
			}
			if (!config.height) {
				config.height = "600px";
			}
			if (OH.modals[id]) {
				modal = cached_modal = OH.modals[id];
			} 
			else {
				modal = new YAHOO.widget.Dialog(id, config);
			}
			
			if (url) {
				if (url.indexOf('aslightbox') === -1){
					url += (url.indexOf('?') === -1 ? '?aslightbox=1' : '&aslightbox=1'); 
				}
				var translationEl = DOM.get('translationRef');
				if (translationEl){
					var translationRef = DOM.get('translationRef').href;
					var langRef = translationRef.split('#')[1];
					if (typeof(langRef) !== "undefined"){
						url += "#"+langRef;
					}
				}
				iframe = '<iframe src="' + url + '" width="' + (parseInt(config.width, 10) - 25) + "px" + '" height="' + (parseInt(config.height, 10) - 25) + "px" + '" name="OHModal" frameborder="0" allowtransparency="true"></iframe>';
			}
	
			if (cached_modal) {
				modal.setBody(iframe);
			} else {
				modal.beforeRenderEvent.subscribe(function ()
				{
					this.element.style.position = 'absolute';
					YAHOO.util.Dom.addClass(modal.innerElement, 'oh-lightbox');
				});
		
				modal.showEvent.subscribe(function () {
					OH.modal = modal;
		
					YAHOO.util.Dom.setStyle(modal.element, 'z-index', config.zIndex);
					YAHOO.util.Dom.setStyle(modal.iframe, 'z-index', config.zIndex);
					YAHOO.util.Dom.setStyle(modal.mask, 'z-index', config.zIndex - 1);
				});
				
				modal.hideEvent.subscribe(function () {
					window.setTimeout(function () {
						top.OH.modal.setBody("");
						if (window.frames["OHModal"]) {
							delete window.frames["OHModal"];
						}
						
					}, 0);
				});
				
				modal.closeEvent = new YAHOO.util.CustomEvent("closeEvent", this); 
				
				modal.setHeader(' ');
				modal.setBody(iframe || ' ');
				modal.render(document.body);
			}
			OH.modals[modal.id] = modal;
			return OH.modals[modal.id];
		} // OH.Modal
	
		OH.modalCancel = function(){
			if (top.OH.modal){ 
				top.OH.modal.hide(); return true; 
			}
			else 
				return false;
		};		
		
		//used only in the old js visualizer
		OH.openURLInModal = function(url, modal){
			modal = modal || new OH.Modal({url: url});
			modal.show();
	
			return modal;
		}; // OH.openURLInModal
		
		//used only on the friends page to remove friends
		OH.Confirm = function(config){
			config = config || {};
			var id = config.id || YAHOO.util.Dom.generateId(),
				defaults = {
					width: "300px",
					visible: false,
					draggable: false,
					close: true,
					zIndex: 999,
					constraintoviewport: true,
					buttons: [
						{ text: "OK", handler: function(){ this.hide(); return true;} },
						{ text: "Cancel", isDefault: true, handler: function(){ this.hide(); return false;} }
					]
				},
				merged = YAHOO.lang.merge(defaults, config);
				var confirm = new YAHOO.widget.SimpleDialog(id, merged);
	
			confirm.renderEvent.subscribe(function(){ this.element.style.position = 'absolute'; });
		   
			if ( config.modal ) { 
				confirm.showEvent.subscribe(function()
				{
					YAHOO.util.Dom.setStyle(confirm.element, 'z-index', config.zIndex);
					YAHOO.util.Dom.setStyle(confirm.mask, 'z-index', config.zIndex - 1);
				});
			}
	 
			confirm.setHeader("Confirm");
			confirm.setBody(' ');
			confirm.setFooter(' ');
			confirm.render(document.body);
	
			return confirm;
		} // OH.Confirm
		
		/* Behaviors for *all* pages. Move to OH.UI.init()? */
		var defaultSkin = 'yui-skin-sam';
		YAHOO.util.Dom.addClass(document.body, defaultSkin);
			
		//wire up quicklinks
		var quickLinks = OH.Selector(".histree-quick-view");
		if (quickLinks.length > 0){
			Event.on(quickLinks, 'click', function(e){
				var origin = Event.getTarget(e);
				var topDiv = DOM.getAncestorByTagName(origin, "div");
				if (topDiv){
					var histreeId = OH.util.onlyInt(topDiv.id);	
					var modal = new OH.Modal({id:'histree-quick-view', url: '/histrees/' + histreeId + '/album', width: "960px", height: "660px"});
					//modal.show();
				}
			});
		}
		
		//wire up connect buttons
		var connectButtons = OH.Selector(".connect-histree");
		if (connectButtons.length > 0){
			Event.on(connectButtons, 'click', function(e){
				Event.preventDefault(e);
				var origin = Event.getTarget(e);
				
				modal = new OH.Modal2({id:'edit-connect', url: origin.href, width: "700px", height: "550px"});
				modal.show();
			});
		}
		
		//wire up send message buttons
		var sendMsgLinks = OH.Selector(".send-message");
        if (sendMsgLinks.length > 0){
            Event.on(sendMsgLinks, 'click', function(e){
				YAHOO.util.Event.preventDefault(e);
				var origin = Event.getTarget(e);
				var parentLI = DOM.getAncestorByTagName(origin, "li");            
				var accountid = OH.util.onlyInt(parentLI.id);
				
				var sendMessage = new OH.Modal({ url: '/messages/compose?recipients[]=' + accountid, width: "600px", height: "350px" });
				sendMessage.show();	
				
			}, this, true);
        }
			
		//wire up branches if there are any
		var headerBranches = OH.Selector("[id^=branch-featured-]");
		if (headerBranches.length > 0){
			Event.on(headerBranches, 'mouseover', ShowFeaturedHistrees, this, true);
		}
		
		//wire up modal to join more branches
		var joinMoreBranches = OH.Selector(".join-more-branches-modal");
		if (headerBranches.length > 0){
			Event.on(joinMoreBranches, 'click', launchBranchJoinSelector, this, true);
		}
		
		var moreDescLinks = OH.Selector(".more-desc-link");
		if (moreDescLinks.length > 0){
			Event.on(moreDescLinks, 'click', function(e){
				Event.preventDefault(e);
				var origin = Event.getTarget(e);
				var fullDesc = DOM.getLastChild(origin.parentNode);
				if (fullDesc){
					origin.parentNode.innerHTML = fullDesc.innerHTML;
				}
			}, this, true);
		}
		
		window.setTimeout(initExternalLibs, 0);
	
		Event.on(document.body, 'click', function(e){
			var target = Event.getTarget(e);
	
			link = (target.nodeName.toUpperCase() === 'A') 
				? target
				: YAHOO.util.Dom.getAncestorByTagName(target, 'a');
	
			if (link && link.href){
	
				if (YAHOO.util.Dom.hasClass(link, 'modal')){
					Event.preventDefault(e);
					var modal = new OH.Modal({
						id: link.id+'-lightbox',
						url: link.href
					});
					modal.show();
				} else if (YAHOO.util.Dom.hasClass(link, 'modal-confirm')){ //used only in communitrees/{id}/payment/join which is still not complete
					Event.preventDefault(e);
					var modal_confirm = new OH.ModalConfirm({
						id: link.id+'-lightbox',
						url: link.href
					});
					modal_confirm.show();
				} else if (YAHOO.util.Dom.hasClass(link, 'help')){//might be used only on the join form to do the CAPTCHA
					Event.preventDefault(e);
					YAHOO.util.Connect.asyncRequest('GET', link.href + '?fragment=1',
					{
						success: function(o)
						{
							help.setBody(o.responseText);
							help.cfg.setProperty('context', [link, 'tl', 'br']);
							help.show();
						}
					});
				}            
			}			
	
		});
		
		// XHR action indicators
		YAHOO.util.Connect.startEvent.subscribe(function(){ OH.util.wait.show(); });
		YAHOO.util.Connect.completeEvent.subscribe(function(){ OH.util.wait.hide(); });
	
		// CSRF functions
		setCSRFHeader();
		YAHOO.util.Connect.failureEvent.subscribe(checkAndSetCSRF);
		YAHOO.util.Connect.successEvent.subscribe(checkAndSetCSRF);
	
		function setCSRFHeader(token){
			if (token){ setCSRFToken(token); }
			YAHOO.util.Connect.initHeader('X-XHR-CSRF', getCSRFToken(), true);
		}
	
		function setCSRFToken(token){ return xhrcsrftoken = token; }
		function getCSRFToken(){ return (typeof(xhrcsrftoken) !== "undefined") ? xhrcsrftoken: null; }
	
		function checkAndSetCSRF(sEvent, args){
			var oResp = args[0], aArgs = args[1],
				resp = YAHOO.lang.JSON.parse(oResp.responseText);
			if (resp.t){ setCSRFHeader(setCSRFToken(resp.t)); }
		}
		
		OH.Application.onLoad.fire();
	}
	
	function initExternalLibs(){
				
		if (window.location.href.indexOf('/histrees/') > -1 && OH.privacy && OH.privacy !== "private"){
			var e = document.createElement('script');
		    e.setAttribute('type', 'text/javascript');
		    e.setAttribute('src', "http://s7.addthis.com/js/250/addthis_widget.js#username=ourhistree");
		    document.getElementsByTagName("head")[0].appendChild(e);
		}
		
		if (OH.Culture !== "CN" && (OH.CommunitreeBrandId === -1 || !OH.CommunitreeBrandId) && !OH.FeaturesDisabled.contains('facebook')){
			
			//Facebook join and login
			//load only on join page
				var e = document.createElement('script'); e.async = true;
				e.src = document.location.protocol +
				  '//connect.facebook.net/en_US/all.js';
				document.getElementById('fb-root').appendChild(e);
			
				window.fbAsyncInit = function() {
					
					FB.init({appId: '3cda0ca3157aafc4e5ef0d4ec04eb792', status: true, cookie: true,
							 xfbml: true});
										
					FB.Event.subscribe('auth.login', function(response) {
						if (response.session){
							if (window.location.href.indexOf('/content/import/') > -1){
								return;
							}
							
							if (window.location.href.indexOf('join') === -1 && window.location.href.indexOf('signin/delete') === -1){								
								pageTracker._trackEvent("User", "Facebook", "Login");
								window.location.href = "/signin?fblogin=true";
							}
							else if (window.location.href.indexOf('signin/delete') > -1){
								//get the querystring and put it into token param
								var qs = window.location.href.split('?');
								var token = qs[1];
								var newUrl = qs[0] + "?fblogin=true&token=" + token
								window.location.href = newUrl;
							}
						}
						else{							
							//alert('You have been logged out of Facebook as well.');
						}
					  });
							
					Event.on(OH.Selector('#signin-form #fbConnectButton'), 'click', function(e){
						Event.preventDefault(e);
						FB.login(function(response){
							if (response.session){
								pageTracker._trackEvent("User", "Facebook", "Login");
								window.location.href = "/signin?fblogin=true";
							}
						});
					});
					
					Event.on('signout', 'click', function(e){
						Event.preventDefault(e);
						
						FB.logout(function(response) {
							// user is now logged out
							//alert('You have been logged out of Facebook as well.');
							
							window.location.href = "/signout";
						});
						
						window.setTimeout(function(){
							window.location.href = "/signout";
							}, 2000);
					});
					
					if (window.location.href.indexOf('signout') > -1 && window.location.href.indexOf('failedfb') > -1 || window.location.href.indexOf('signin/delete') > -1){
						FB.logout();									
					}
				};
				
			
		}
		
	}
	
	function launchBranchJoinSelector(e){
		Event.preventDefault(e);
		
		modal = new OH.Modal2({id: "join-more-branches", url: '/communitrees/' + OH.CommunitreeId + '/branches/select?ref=joinmore', width: "650px", height: "390px"});
		modal.show();
	}
	
	function ShowFeaturedHistrees(e){
		var origin = Event.getTarget(e);
		var branchId = OH.util.onlyInt(origin.id);
		
		if (YAHOO.lang.isNumber(branchId) && !branchesLoaded.contains(branchId)){
			var params = { "communitreeid" : branchId }
			//get featured histrees			
			YAHOO.util.Connect.asyncRequest('GET', '/xhr/featuredhistrees/get?'+OH.util.obj2URL(params), {
					scope: this,
					success: function(o){						
						var response = YAHOO.lang.JSON.parse(o.responseText);
						var histrees = response.r;						
						
						//Put histree info into the empty LI
						var histreesHolder = OH.Selector("li", origin)[0];
						if (histreesHolder){
							histreesHolder.innerHTML = "<h4>Featured</h4>";
							for (var i=0; i<histrees.length; i++){
								histreesHolder.innerHTML += YAHOO.lang.substitute(HistreeTemplate, histrees[i], OH.util.formatHistree);
							}
						}
						branchesLoaded.push(branchId);
					},
					failure: function(o){
						var response = YAHOO.lang.JSON.parse(o.responseText);
						alert(response.e);
					}

				})
		}
	}

	HistreeTemplate = '<p><a class="histree-name" href="/histrees/{histreeid}">{name}</a></p><div><a href="/histrees/{histreeid}"><img src="{thumbnail}" /></a></div>';
	
	
	Event.onDOMReady(YUILoadComplete);

})();



