/**
 * Songpier Application
 *
 * @author    
 * @copyright (c) 
 * @date      
 * @version   $Id$
 *
 * @license songpier.js is licensed under the terms of the Open Source
 * LGPL 3.0 license. Commercial use is permitted to the extent that the 
 * code/component(s) do NOT become part of another Open Source or Commercially
 * licensed development library or toolkit without explicit permission.
 * 
 * License details: http://www.gnu.org/licenses/lgpl.html
 */


function Songpier() {
	
	this.initialized=false;
	
	//---------------------------------------------------------------------------------------
	this.init = function() {
		if(this.initialized == true) return;
		this.initialized = true;
		/*
		this.setFooter('footerContainer','mainContainer');
		Ext.EventManager.addListener(window,'resize',function() {SP.setFooter('footerContainer','mainContainer')},this);		
		*/
		if(typeof loadFlowConf == 'function') loadFlowConf();
		this.initTabs();
		if(Ext.get('mainCaroussel')) { // home carousel
			var conf = {itemSelector: 'div.carousselScreen'};
			if(typeof startSlide != 'undefined') conf.startSlide = parseInt(startSlide);
			if(typeof sfn != 'undefined' && sfn == 'play') conf.startfn = SP.playHomeVideo;
			this.crsl = new Songpier.Carousel('mainCaroussel',conf);
		}
		//this.preloadImgs = [{src:'/images/songpier/carousel/arrow-left-off.png'},{src:'/images/songpier/carousel/arrow-right-off.png'}];		
		//if(typeof this.preloadImgs == 'object') this.preloadImages.defer(500,this,[this.preloadImgs]);		
		this.clearOnFocus();
		
		//this.hideRegistrationForms.defer(100,this);
		
		var featuredsongs = Ext.get('featuredsongs');
		
		if(featuredsongs) {
			this.fts = new Songpier.FeaturedSongs('featuredsongs',{});
			
			this.preloadImgs = [
				{src:'/images/songpier/home-onestop/preview-icons/mobile.png'},
				{src:'/images/songpier/home-onestop/preview-icons/pad.png'},
				{src:'/images/songpier/home-onestop/preview-icons/desktop.png'},
				{src:'/images/songpier/home-onestop/preview-icons/facebook.png'}
			];		
			if(typeof this.preloadImgs == 'object') this.preloadImages.defer(500,this,[this.preloadImgs]);		

		}
		
	}
	
	this.NLSignUp = function(f) {

		var form = Ext.get(f);
		var fieldset = Ext.get(Ext.DomQuery.selectNode('div.fieldset',form.dom));
		var error = Ext.get(Ext.DomQuery.selectNode('div.error',form.dom));
		var email = Ext.get(Ext.DomQuery.selectNode('input.email',form.dom)); 
		error.setVisibilityMode(Ext.Element.DISPLAY);

		if(!email.dom.value || email.dom.value.length==0 || email.dom.value == 'Email') {
			error.update('Please tell us your email address');
			error.show(true);
			this.setRightContent();
			return false;
		}
		
		var mask = this.mask(fieldset,{loading:true,opacity:.85,bwidth:0,bheight:0});
		
		Ext.Ajax.request({
			url: '/plugins/mailchimp.php',
			scope:this,
			form:form,
			mask:mask,
			error:error,
			success: function(response, opts) {
				var responseData = Ext.util.JSON.decode(response.responseText);
				if(responseData && responseData.success == true) {
					var fields  = opts.form.select('input');
					fields.setVisibilityMode(Ext.Element.DISPLAY);
					fields.hide();
					var trigger = Ext.get(Ext.DomQuery.selectNode('div.triggers',opts.form.dom));
					trigger.setVisibilityMode(Ext.Element.DISPLAY);
					trigger.hide();
					var u = 'Thanks!';
					opts.error.addClass('success');
				} else {
					var u = 'Subscription failed. Please try again later';
				}
				if(u) {
					opts.error.update(u);
					opts.error.show(true);
				} else {
					error.update('');
					opts.error.hide(true);
				}
				opts.mask.remove();
				this.setRightContent();
			},
			failure: function(response, opts) {
				opts.error.update('Subscription falied. Please try again later');
				opts.error.show(true);
				opts.mask.remove();
				this.setRightContent();
			}
		});		
		
	}
	
	//---------------------------------------------------------------------------------------
	this.check4LoginReturn = function(event,f) {
		if(typeof event == 'undefined' || !event) return true;
		var obj = event.target || event.srcElement;
		if(obj.type == "submit") return true;
		if(obj.type != "textarea" && event && event.keyCode == 13 ){
			if(event.preventDefault) event.preventDefault()
			else event.returnValue = false;
			this.login(f);
		};
		return true;
	};
	this.login = function(f) {

		var form = Ext.get(f);
		var fieldset = Ext.get(Ext.DomQuery.selectNode('div.fieldset',form.dom));
		var error = Ext.get(Ext.DomQuery.selectNode('div.error',form.dom));
		error.setVisibilityMode(Ext.Element.DISPLAY);
		var mask = this.mask(fieldset,{loading:true,opacity:.85,bwidth:-4,bheight:0});

		Ext.Ajax.request({
			url: 'index.php',
			scope:this,
			form:form,
			mask:mask,
			error:error,
			success: function(response, opts) {
				var responseData = Ext.util.JSON.decode(response.responseText);
				if(responseData && responseData.success == true) {
					if(responseData.data 
					&& responseData.data.redirect
					&& responseData.data.redirect.length > 0) {
						var fields  = opts.form.select('input');
						fields.setVisibilityMode(Ext.Element.DISPLAY);
						fields.hide(true);
						var trigger = Ext.get(Ext.DomQuery.selectNode('div.triggers',opts.form.dom));
						trigger.setVisibilityMode(Ext.Element.DISPLAY);
						trigger.hide(true);
						var u = 'Successfully logged in. Please click <a style="font-weight:bold;" href="'+responseData.data.redirect+'">here</a> if the automatic redirection does not work.';
						opts.error.addClass('success');
						location.href = responseData.data.redirect;
					} else {
						var u = 'Login failed: something went wrong, please contact the webmaster..';
					}
				} else {
					var u = 'Login failed: something went wrong, please contact the webmaster..';
					if(responseData && responseData.error && responseData.error.code) {
						switch(responseData.error.code) {
							case 404:
								var u = 'You are already logged in. Please click on the Link "Artist" in the menu on top of the page.'
								break;
							case 400:
								var u = 'Login failed: wrong username or password.';
								if(responseData.error 
								&& responseData.error.form 
								&& responseData.error.form.field == 'username') {
									var u = 'Login failed: this username is not known.';
								} else if(responseData.error 
								&& responseData.error.form 
								&& responseData.error.form.field == 'password') {
									var u = 'Login failed: your password is wrong.';
								}
								break;
							default:
						}
					}
				}
				if(u) {
					opts.error.update(u);
					opts.error.show(true);
				} else {
					error.update('');
					opts.error.hide(true);
				}
				opts.mask.remove();					
			},
			failure: function(response, opts) {
				opts.error.update('Login falied: wrong username or password.');
				opts.error.show(true);
				opts.mask.remove();
			}
		});		
		
	}
	
	this.signUp = function(f) {
	
		var form = Ext.get(f);
		var fieldset = Ext.get(Ext.DomQuery.selectNode('div.fieldset',form.dom));
		var error = Ext.get(Ext.DomQuery.selectNode('div.error',form.dom));
		error.update('');
		error.setStyle('display','none');
		var mask = this.mask(fieldset,{loading:true,opacity:.85,bwidth:2,bheight:2});
		var ipts = Ext.DomQuery.select('input',form.dom);
		for(var i=0;i<ipts.length;i++) { if(typeof console == 'object') console.log('x '+ i+': %o',ipts[i]); if(ipts[i].id) Ext.get(ipts[i].id).removeClass('errorfield'); }
		var ists = Ext.DomQuery.select('select',form.dom);
		for(var i=0;i<ists.length;i++) { if(ists[i].id) Ext.get(ists[i].id).removeClass('errorfield'); }
		
		Ext.Ajax.request({
			url: 'index.php',
			scope:this,
			form:form,
			mask:mask,
			error:error,
			success: function(response, opts) {
				opts.mask.remove();	
				var responseData = Ext.util.JSON.decode(response.responseText);
				if(typeof console == 'object') console.log('x responseData: %o',responseData);
				if(responseData && responseData.success == true) {
					// show thank you message
					var signup_fieldset = Ext.get('signup_fieldset');
					if(signup_fieldset) {
						var mask_signup_fieldset = this.mask(signup_fieldset,{
							loading:false,
							opacity:.85,
							bwidth:2,
							bheight:2,
							content:[ 
								{tag: 'div', cls: 'comingSoon', 
									children: [ 
										{tag: 'img', src:'/images/songpier/form/thank_you.png'}
									]				
								}
							]
						});
					}						
					return;
				} else {
					if(typeof responseData.error == 'object') {
						switch(responseData.error.code) {
							case 400:
							default:
								opts.error.update('Sign up failed!');
								opts.error.setStyle('display','block');
						}						
					}					
					if(typeof responseData.error.form == 'object') {
						if(responseData.error.form.field) {
							var field = Ext.get('signup_'+responseData.error.form.field);
							if(typeof console == 'object') console.log('x field '+responseData.error.form.field+': %o',field);
							if(field) {
								if(typeof console == 'object') console.log('x field: %o',field);
								field.addClass('errorfield');
							}
						}
					}

				}
								
			},
			failure: function(response, opts) {
				//opts.error.update('Sorry, login failed: error code ' + response.status);
				opts.error.update('Login falied: wrong username or password.');
				opts.error.setStyle('display','block');
				opts.mask.remove();
			}
		});	
	}
	this.widgetEl=false;
	//---------------------------------------------------------------------------------------
	this.previewQRWidget = function(e,f) {
		
		if(!this.widgetEl) {
			this.widgetEl = Ext.get('songpier');
		}
		
		if(!this.widgetEl.isVisible() || f == true) {
			if(typeof Ext == 'object' && !this.widgetEl.isVisible()) {
				this.widgetEl.fadeIn({
					endOpacity: 0, 
					duration: .15,
					easing:'easeOut'
				});
			} else this.widgetEl.show();
		} else this.widgetEl.hide();

		if(!this.widgethideme) {
			this.addEvent(document,'mousedown',SP.widgethideme = function(event) {this.hideQRWidget(event);}.bind(this));
		}
		
		if (e && e.stopPropagation) {
			e.stopPropagation();
		} else if(e) {
			e.cancelBubble = true;
		} 		
	}
	
	//---------------------------------------------------------------------------------------
	this.hideQRWidget = function(event) {
		var el = this.gettarget(event);
		if (el == this.widgetEl.dom) return;
		if(el && el.id && el.id == 'qrwidgetlink') return;
		var p = el.parentNode;
		var maxP = 10;
		while(p) {
			if(p
			&& p.id
			&& p.id == 'songpier') return;
			if(maxP == 0) p = false;
			p = p.parentNode;
			maxP--;
		}
		
		if(typeof Ext == 'object') {
			this.widgetEl.fadeOut({
				endOpacity: 0, 
				duration: .15,
				easing:'easeIn'
			});
		} else this.widgetEl.hide();
		this.removeEvent(document,'mousedown',SP.widgethideme);
		this.widgethideme=false;
	}	
	
	this.isDevice = function() {
		nav = navigator;
		ua = nav.userAgent.toLowerCase();		
		check = function(r){
			return r.test(ua);
		};
		var devIsDevice = check(/iphone|ipod|ipad|android/gi);
		if(devIsDevice) {
			return true;
		} else return false;
	}
	//---------------------------------------------------------------------------------------
	this.loadEmulator = function(v,artist,song) {

		var src = '/'+artist;
		if(song && song.length>0) src = src+'/'+song;

		if(this.isDevice()) {
			window.open(src);
			return false;
		}
		// scroll up, cause ff scrolls anyway, if body gets overflow hidden
		window.scrollTo(0, 10);
		
		// Phone
		var phoneEmulator = Ext.get('phoneEmulator');
		var phoneWR = Ext.get('PhoneEmulatorWrapper');
		
		// Pad
		var padEmulator = Ext.get('PadEmulator');
		var PadEmulatorScroller = Ext.get('PadEmulatorScroller');
		var padWR = Ext.get('PadEmulatorWrapper');
		
		// Facebook
		var fbEmulator = Ext.get('FacebookEmulator');
		var fbWR = Ext.get('FacebookEmulatorWrapper');
		
		var st = this.docScrollTop();
		var b = {};
		b.width = Ext.getBody().getWidth();
		b.height = (typeof window.innerHeight == 'undefined') ? document.documentElement.clientHeight : window.innerHeight;
		this.coverbackground(true,{op:0.85});

		switch(v) {
			case'Phone':
				var h=750; var w=380;
				var x = (b.width/2) - (w/2);
				var y = (st+(b.height/2)) - (h/2);	
				if(y<0) y = 10;
				phoneWR.setStyle({left:x+'px',top:y+'px'});	
				phoneWR.setStyle('display','block');
				//PadEmulatorScroller.setStyle('display','none');
				phoneEmulator.dom.src=src+'?_=m';
				this.addEvent(this.cover,'click',this.hideme = function(event) {SP.hideOverlay(event,phoneWR.id); });
				break;
			case'Pad':
				var h=750; var w=952;
				var x = (b.width/2) - (w/2);
				var y = (st+(b.height/2)) - (h/2);	
				if(y<0) y = 10;
				PadEmulatorScroller.setStyle({left:x+'px',top:y+'px'});	
				//phoneWR.setStyle('display','none');
				PadEmulatorScroller.setStyle('display','block');
				padEmulator.dom.src=src+'?_=p&scale=0.8';
				this.addEvent(this.cover,'click',this.hideme = function(event) {SP.hideOverlay(event,PadEmulatorScroller.id); });
				break;
			case'Facebook':
				var h=830; var w=952;
				var x = (b.width/2) - (w/2);
				var y = (st+(b.height/2)) - (h/2);	
				if(y<0) y = 10;
				fbWR.setStyle({left:x+'px',top:y+'px'});	
				fbWR.setStyle('display','block');
				//PadEmulatorScroller.setStyle('display','none');
				fbEmulator.dom.src=src+'?_=f&_preview=1';
				this.addEvent(this.cover,'click',this.hideme = function(event) {SP.hideOverlay(event,fbWR.id); });
				break;
		}
		
		this.activeEmulator = v;
	}
	
	this.docScrollTop = function() {
		if ( document.documentElement && document.documentElement.scrollTop ) {
			return document.documentElement.scrollTop;
		} else if ( document.body ) {
			return document.body.scrollTop;
		} else if ( window.pageYOffset ) {
			return window.pageYOffset;
		} else {
			return 0;
		}
	}	
   
	//---------------------------------------------------------------------------------------
	this.hideOverlay = function(event,id,force) {
		if(!force) {
			var el;
			if(event) {
				el = this.gettarget(event);
				if (el == $(id+'_overlay')) return;
				if (el == $(id+'')) return;
			}
			el = el.parentNode;
			while(el) {
				if(el.parentNode
				&& el.parentNode.id
				&& el.parentNode.id == (id+'_overlay')) return;
				el = el.parentNode;
			}
		}
		
		var overlay = Ext.get(id);
		if(overlay) {
			overlay.setStyle('display','none');
			var iframe = overlay.select('iframe');
			if(iframe) {
				this.stopPlayer(iframe.elements[0]);
			}
		}
		this.coverbackground(false);
		this.removeEvent(this.cover,'click',this.hideme);
	}	

	this.stopPlayer = function(IFrame) {
		if(window.frames) var IFrameObj = window.frames[IFrame.id];
		if(!IFrameObj) return false;
		if(IFrameObj 
		&& IFrameObj.player
		&& IFrameObj.player.playbackModule) {
			if(!IFrameObj.player.playbackModule.paused) IFrameObj.player.playbackModule.pause();
		}
	}
	
	//---------------------------------------------------------------------------------------
	this.coverbackground = function(vs,p) {

		if(typeof p != 'object') p = {};
		if(!p.bg_color) p.bg_color = "#ffffff";
		if(!p.op) p.op = 1;
		
		if(!this.cover) {
			this.cover = document.createElement('div');
			this.cover.style.position = 'absolute';
			this.cover.style.zIndex = 5;
			this.cover.style.left = 0+'px';
			this.cover.style.top = 0+'px';
			this.cover.style.opacity = p.op; // set opacity for effect : filter:alpha(opacity=50); -moz-opacity:0.5; opacity:0.5; 
			this.cover.style.filter = "alpha(opacity:"+Math.round(p.op*100)+")";
			this.cover.style.backgroundColor = p.bg_color;
			document.getElementsByTagName('body')[0].appendChild(this.cover);
		}
		
		if(!vs) {
			this.cover.style.visibility = 'hidden';
			var b = document.getElementsByTagName('body');
			if(b && b[0]) b[0].style.overflow = 'auto';
			var h = document.getElementsByTagName('html');
			if(h && h[0]) h[0].style.overflow = 'auto';
		} else {
			var ww = Ext.getBody().getWidth();
			var wh = Ext.getBody().getHeight();
			var st = Ext.getBody().getScroll();
			bodyheight = st.top+wh;
			bodyheight = document.body.offsetHeight;
			if(wh > bodyheight) bodyheight = wh;
			this.cover.style.width = '100%';
			this.cover.style.height = (bodyheight)+'px';
			this.cover.style.visibility =  'visible';			
			var b = document.getElementsByTagName('body');
			if(b && b[0]) b[0].style.overflow = 'hidden';
			var h = document.getElementsByTagName('html');
			if(h && h[0]) h[0].style.overflow = 'hidden';

		}		
	}	
	//---------------------------------------------------------------------------------------
	this.register = function(f) {
		var form = Ext.get(f);
	}
	//---------------------------------------------------------------------------------------
	this.mask = function(f,p) {
		var d = {loading:true,opacity:.75};
		if(typeof p != 'object') var p = {};
		p = Ext.apply(d,p);
		f.setStyle('position','relative');
		var dh = Ext.DomHelper;
		var spec = {
			tag: 'div',
			cls: 'mask',
			style: 'width: 10px;',
			id:'loaderwr'+f.id
		};
		
		if(p.loading) { 
			spec.children = [ 
				{tag: 'div', cls: 'loader', id:'loadermgs'+f.id,
					children: [ 
						{tag: 'img', cls: 'loader-img', src:'/images/songpier/form/loading.gif'}
					]				
				}
			];
		}
		if(p.content) spec.children = p.content;
		
		var mask = dh.insertFirst(f,spec,true);
		mask.setOpacity(p.opacity,true);
		if(typeof p.bwidth != 'number') p.bwidth = 0;
		if(typeof p.bheight != 'number') p.bheight = 0;
		mask.setStyle({
			width: (f.getWidth()-p.bwidth)+'px',
			height: (f.getHeight()-p.bheight)+'px',
			display:'block'
		});
		return mask;
	}
	//---------------------------------------------------------------------------------------	
	this.goAndPlayVideo = function() {
		this.crsl.startSlideFN = SP.playHomeVideo;
		this.crsl.setSlide(2);	
	}
	
	this.playHomeVideo = function() {

		var mp4movie = $('mp4movie');
		if(mp4movie && typeof mp4movie.play == 'function') {
			TV.playHTML5Video('mp4movie');
		}

		if(typeof flowplayer == 'function') {
			var flowmovie = flowplayer('flowmovie');
			if(flowmovie && typeof flowmovie.play == 'function') flowmovie.play();
		}		
	}
	//---------------------------------------------------------------------------------------
	this.initTabs = function() {
		// go through items classname tabs
		var tabs = Ext.DomQuery.select('div.tabs');
		var TB = [];
		for(i=0;i<tabs.length;i++) {
			TB[i] = new Songpier.Tabs();
			TB[i].init(tabs[i]);
		}
	}	
	//---------------------------------------------------------------------------------------
	this.preloadImages = function(images){
        var preload = Ext.get(document.body).createChild({tag:"div", style:"display:none"});
        if(images && images.length > 0) {
			Ext.each(images, function(image){
				if (typeof(image)=='string'){
				 image={src:image}
				}
								
				if (image.src){
					preload.createChild({tag:"img", src:image.src});
				}
				
				if (image.fullSrc){
					preload.createChild({tag:"img", src:image.fullSrc});
				}
			}, this);
        } else if(typeof images == 'object') {
        	for(img_sid in images) {
  				if (images[img_sid].src){
					preload.createChild({tag:"img", src:images[img_sid].src});
				}      		
        	} 
        }
    }
    //---------------------------------------------------------------------------------------
	this.check4Return = function(event) {
		if(typeof event == 'undefined' || !event) return true;
		var obj = event.target || event.srcElement;
		if(obj.type == "submit") return true;
		if(obj.type != "textarea" && event && event.keyCode == 13 ){
			if(event.preventDefault) event.preventDefault()
			else event.returnValue = false;
		};
		return true;
	};
	//---------------------------------------------------------------------------------------
	this.clearOnFocus = function() { // ext version
		/**
		* Clears all input/textareas with classname "cof" (clearonfocus)
		* on uses focus-Mouseevent.
		*/

		var cofs = Ext.DomQuery.select('.cof');
		
		Ext.each(cofs,function(input) {
			var input = Ext.get(input);
			input._defaultValue = input.getAttribute('title');
			if((!input.id) || (input.id.length == 0)) input.id = 'id'+new Date().format('YmdHis')+'_'+(1+Math.floor((Math.random()*32767)));
			input.dom.removeAttribute('title');
			
			if(typeof (Ext.ToolTip) == 'object') {
				input.qtip = new Ext.ToolTip({
					target: input.id,
					cls:'xlocal',
					anchor: 'top',
					autoHide: true,
					dismissDelay:0,
					anchorOffset: 10,
					html: input._defaultValue
				});
			}
			
			input.addListener('focus', function(ev,input) {
				var input = Ext.get(input);
				if(input.getValue() == input._defaultValue) {
					$(input.id).value = '';					
				}
				input.addClass('on-focus');
				if(typeof (Ext.ToolTip) == 'object') input.qtip.show();
			});
			input.addListener('blur', function(ev,input) {
				var input = Ext.get(input);
				if(input.getValue() == '') {
					$(input.id).value=input._defaultValue;
				}
				input.removeClass('on-focus');	
				if(typeof (Ext.ToolTip) == 'object') input.qtip.hide();
			});
			
		});	
	}	

	//---------------------------------------------------------------------------------------
	this.setRightContent = function() {	
		// must called onload because fonts needs to be loaded to get the correct result of blogContens height
		var rightBox = Ext.get('rightBox');
		var blogContent = Ext.get('blogContent');
		var loginWR = Ext.get('loginWR');
		var flexBox = Ext.get('flexBox');
		if(blogContent && rightBox && blogContent.dom && blogContent.dom.offsetHeight) {
			var h = (blogContent.dom.offsetHeight-(rightBox.dom.offsetHeight-loginWR.dom.offsetHeight));
			var bd = 3; // 2 = border
			if(flexBox.dom.offsetHeight>20) bd=0;
			var h = (blogContent.dom.offsetHeight-(rightBox.dom.offsetHeight-loginWR.dom.offsetHeight-flexBox.dom.offsetHeight)-17); // 17 flexBox padding
			flexBox.setStyle('height',(h+bd) + 'px'); 
			rightBox.setStyle('visibility','visible');
		}
	}
	//---------------------------------------------------------------------------------------
	this.setFooter = function(f_id,c_id,setfootercomplete) {
	
		if(typeof f_id == 'undefined') f_id = 'footer';
		if(typeof c_id == 'undefined') c_id = 'coctect';
		
		if(!document.getElementById(f_id)) return;
		if(!document.getElementById(c_id)) return;
		
		ft = document.getElementById(f_id);
		ct = Ext.get(c_id);
	
		var ctXY = ct.getXY();
		var wHeight = this.getWindowHeight();
		var pHeight = document.body.offsetHeight;
		
		if(pHeight
		&& wHeight
		&& pHeight<wHeight) {
			var new_height = (parseInt(wHeight) - parseInt(ft.offsetHeight) - ctXY[1]);
			ct.setStyle('height',new_height+'px'); 
		}
		
		if(typeof setfootercomplete == 'function') {
			setfootercomplete.defer(100,this,[this,f_id,c_id]);
		}
	}
    //---------------------------------------------------------------------------------------
	this.getWindowHeight = function() {
		var h;
		
		if(window
			&& window.innerHeight
			&& window.innerHeight > 0
		) {
			h = window.innerHeight;
		} 
		else if(document
			&& document.documentElement
			&& document.documentElement.clientHeight
			&& document.documentElement.clientHeight > 0
		) {
			h = document.documentElement.clientHeight;
		} else if(document
			&& document.body
			&& document.body.clientHeight
			&& document.body.clientHeight > 0
		) {
			h = document.body.clientHeight;
		} else if(document
			&& document.body
			&& document.body.offsetHeight
			&& document.body.offsetHeight > 0
		) {
			h = document.body.offsetHeight;
		}
		
		return h;
	}	
    //---------------------------------------------------------------------------------------
	this.bind = function(obj, cback, fun, capture) {
		if (obj.addEventListener)
		{
			obj.addEventListener(cback, fun, !!capture);
		}
		else if (obj.attachEvent)
		{
			if (cback == 'DOMContentLoaded')
				cback = 'load';
			obj.attachEvent("on"+cback, fun);
		}
	}
    //---------------------------------------------------------------------------------------
	this.gettarget = function(event) {

		if(window
		&& (window.event)
		&& (window.event.srcElement)) {
			t = window.event.srcElement;
		} else {
			t = (event.target.tagName ? event.target : event.target.parentNode);
		}
		return t;
	}	
	//---------------------------------------------------------------------------------------
	this.addEvent = function(el,evname,func) {
		if (el.attachEvent) { // IE
			el.attachEvent("on" + evname, func);
		} else if (el.addEventListener) { // Gecko / W3C
			el.addEventListener(evname, func, true);
		} else {
			el["on" + evname] = func;
		}
	}
	//---------------------------------------------------------------------------------------
	this.removeEvent = function(el,evname,func) {
	
		if (el.detachEvent) { // IE
			el.detachEvent("on" + evname, func);
		} else if (el.removeEventListener) { // Gecko / W3C
			el.removeEventListener(evname, func, true);
		} else {
			el["on" + evname] = null;
		}
	} 	
}

var SP = new Songpier();
//SP.bind(window, 'DOMContentLoaded', function() { SP.setRightContent(); }, false);
SP.bind(window, 'load', function() { SP.setRightContent(); }, false);

if(typeof Ext == 'object') {

	//---------------------------------------------------------------------------------------
	Ext.onReady(function() {
		Ext.BLANK_IMAGE_URL = '/images/spacer.gif';
		SP.init();
	});
	//Ext.EventManager.onDocumentReady(function() { alert('onDocumentReady'); SP.init(); });
	//Ext.EventManager.addListener(document,'DOMContentLoaded',function() {  SP.init(); });
	
	
	//---------------------------------------------------------------------------------------
	Songpier.Tabs = function() {
		
		this.selectedTab = false;
		
		this.init = function(tel) {
			this.parent = Ext.get(tel);
			if(!this.parent) return false;
			// get all hrefs and initialize tab and search for selected tab
			var ahrefs = Ext.DomQuery.select('a',tel);
			for(a=0;a<ahrefs.length;a++) {
				var xEL = Ext.get(ahrefs[a]);
				if(xEL.hasClass('selected')) this.selectedTab = xEL;
				xEL.addListener('click',this.selectTab,this,{xEL:xEL,preventDefault:true});
			}
		}
		
		this.selectTab = function(ev,el,o) {
			if(typeof SP.crsl == 'object') SP.crsl.pause();
			var tabs = Ext.get('tabs');
			if(this.selectedTab) {
				if(tabs) tabs.removeClass(this.selectedTab.id);		
				this.selectedTab.removeClass('selected');
				var lEl = Ext.get('tabContent-'+this.selectedTab.id);
				lEl.setStyle('display','none');
			}
			var xEl = o.xEL;
			xEl.addClass('selected');
			if(tabs) tabs.addClass(xEl.id);
			xEl.blur();
			var nlEl = Ext.get('tabContent-'+xEl.id);
			nlEl.setStyle('display','block');
			this.selectedTab = xEl;
			return false;
		}
	}
	//---------------------------------------------------------------------------------------
	Songpier.FeaturedSongs = Ext.extend(Ext.util.Observable, {

		constructor: function(elId, config) {
			config = config || {};
			Ext.apply(this, config);
			Songpier.FeaturedSongs.superclass.constructor.call(this, config);
			if(SP.isDevice()) return false;
			this.el = Ext.get(elId);
			this.els = [];
			this.initMarkup();
			this.initEvents();
		},
		
		initMarkup: function() {
			this.els.items = this.el.select('a.cornerstone');
		},
		
		initEvents: function() {
			this.els.items.on('mouseenter', function(e,t,o){
				var xt = Ext.get(t);
				if(xt.hasClass('cornerstone')) var p = xt;
				else var p = xt.up('a.cornerstone');
				if(p) {
					var icon = p.down('span.cornerstoneIconBG');
					if(icon && icon.isVisible()) {
						icon.slideOut('t', {
							easing: 'easeOut',
							duration: 0.25,
							remove: false,
							useDisplay: true
						});
					}
				}
				
			}, this);
			this.els.items.on('mouseleave', function(e,t,o){
				var xt = Ext.get(t);
				if(xt.hasClass('cornerstone')) var p = xt;
				else var p = xt.up('a.cornerstone');
				if(p) {
					var icon = p.down('span.cornerstoneIconBG');
					if(icon && (!icon.isVisible())) {
						icon.slideIn('t', {
							easing: 'easeIn',
							duration: 0.25,
							remove: false,
							useDisplay: true
						});
					}
				}
				
			}, this,{buffer: 1000});
			
			Ext.getBody().on('mousemove',this.qtip,this);
		},
		
		qtip: function(e,t,o) {
			if(!this.qtipEl) {
				this.qtipEl = this.createQtip();
			}
			if(t 
			&& typeof t.getAttribute == 'function'
			//&& (!this.qtip.isVisible())
			&& t.getAttribute('qtip')) {
				var tip = t.getAttribute('qtip');
				if(this.qtipEl.dom.innerHTML != tip) this.qtipEl.dom.innerHTML = tip;
				var pos = e.getXY();
				pos[0] = pos[0]+10;
				pos[1] = pos[1]+10;
				this.qtipEl.setXY(pos); 
				if(!this.qtipEl.isVisible()) this.qtipEl.show();
			} else this.qtipEl.hide();
		},
		
		createQtip: function() {
			return Ext.DomHelper.append(Ext.getBody(),{
				tag:'div',
				cls:'qtip'},
			true);
		}
		
	});

	//---------------------------------------------------------------------------------------
	Songpier.Carousel = Ext.extend(Ext.util.Observable, {
		interval: 7,
		transitionDuration: 0.5,
		transitionType: 'carousel',
		transitionEasing: 'easeOut',//'easeOut', 'elasticOut'
		itemSelector: 'img',
		activeSlide: 0,
		startSlide: 0,
		autoPlay: true,
		autoPlayStart: 60,//(1000*60*30),
		showPlayButton: false,
		pauseOnNavigate: true,
		wrap: false,
		freezeOnHover: true,
		navigationOnHover: false,
		hideNavigation: false,
		width: null,
		height: null,
	
		constructor: function(elId, config) {
			config = config || {};
			Ext.apply(this, config);
			
			Songpier.Carousel.superclass.constructor.call(this, config);
			
			this.addEvents(
				'beforeprev',
				'prev',
				'beforenext',
				'next',
				'change',
				'play',
				'pause',
				'freeze',
				'unfreeze'
			);
			
			this.el = Ext.get(elId);
			this.slides = this.els = [];
			this.btnavImgs = [];
			
			if(this.autoPlay || this.showPlayButton) {
				this.wrap = true;
			};
			
			if(this.autoPlay && typeof config.showPlayButton === 'undefined') {
				this.showPlayButton = true;
			}
			
			this.initMarkup();
			this.initEvents();
			
			if(this.carouselSize > 0) {
				this.refresh();
			}
			
			if(this.startSlide > 0 && this.activeSlide != this.startSlide) {
				if(typeof this.startfn == 'function') this.startSlideFN = this.startfn;
				this.setSlide.defer(1000,this,[this.startSlide]);	
			}
		},
	
		initMarkup: function() {

			this.carouselSize = 0;
			// slides
			var items = this.el.select(this.itemSelector);
			this.els.navBottom = Ext.get(this.el.select('div.carousselNavi',true).elements[0]);
			// slide container
			this.els.container =  Ext.get(this.el.select('div.carousselContainer',true).elements[0]);
			this.els.slidesWrap =  Ext.get(this.el.select('div.innerCaroussel',true).elements[0]);
			
			// set the dimensions of the container
			this.containerWidth = this.width || this.el.getWidth(true);
			this.containerHeight = this.height || this.el.getHeight(true);

			// set dimensions of the slide
			this.slideWidth = this.containerWidth;
			this.slideHeight = this.containerHeight-this.els.navBottom.getHeight();
			
			
			this.els.container.setStyle({
				width: this.slideWidth + 'px',
				height: this.slideHeight + 'px'
			});
			
			Ext.each(items.elements,function(item){
				// set slides with and height and fill slides array
				xitem = Ext.get(item); this.slides.push(xitem);
				xitem.setWidth(this.slideWidth + 'px').setHeight(this.slideHeight + 'px');
				// create bottom nav
				var btnavImg = Ext.DomHelper.append(this.els.navBottom,{tag:'img',cls:'cl-navi',src:'/images/songpier/home-onestop/cl-navi-off.png'},true);
				this.btnavImgs.push(btnavImg);
			},this);
			
			this.carouselSize = this.slides.length;
		},
	
		initEvents: function() {

			for(bidx=0;bidx<this.btnavImgs.length;bidx++) {
				this.btnavImgs[bidx].addListener('click',function(ev,el,o){
					ev.preventDefault();
					var target = ev.getTarget();
					target.blur();
					this.pause();
					/*if(this.playing) {
						this.fireEvent('freeze', this.slides[this.activeSlide]);
						Ext.TaskMgr.stop(this.playTask);
					}*/
					this.setSlide(o.bidx);
					this.play.defer(this.autoPlayStart,this);
				},this,{preventDefault:true,bidx:bidx});
			}

			if(this.freezeOnHover) {
				this.els.container.on('mouseenter', function(){
					if(this.playing) {
						this.fireEvent('freeze', this.slides[this.activeSlide]);
						Ext.TaskMgr.stop(this.playTask);
					}
				}, this);
				this.els.container.on('mouseleave', function(){
					if(this.stopPlaying) return true;
					if(this.playing) {
						this.fireEvent('unfreeze', this.slides[this.activeSlide]);
						Ext.TaskMgr.start(this.playTask);
					}
				}, this, {buffer: (this.interval/2)*1000});
			};			
			if(this.interval && this.autoPlay) {
				this.play.defer(this.autoPlayStart,this);
			};			
		},
				
		prev: function() {
			if (this.fireEvent('beforeprev') === false) {
				return;
			}
			if(this.pauseOnNavigate) {
				this.pause();
			}
			this.setSlide(this.activeSlide - 1);
	
			this.fireEvent('prev', this.activeSlide);        
			return this; 	
		},
		
		next: function() {
			if(this.fireEvent('beforenext') === false) {
				return;
			}
			if(this.pauseOnNavigate) {
				this.pause();
			}
			this.setSlide(this.activeSlide + 1);
	
			this.fireEvent('next', this.activeSlide);        
			return this;  		  
		},
	
		pause: function() {
			if(this.playing) {
				Ext.TaskMgr.stop(this.playTask);
				this.playTaskBuffer.cancel();
				this.playing = false;
				if(this.showPlayButton) {
					if(this.els.navPlay) this.els.navPlay.removeClass('ux-carousel-playing');
				}
				this.fireEvent('pause');
			}        
			return this;	
		},

		play: function() {
			if(!this.playing) {
				this.playTask = this.playTask || {
					run: function() {
						this.playing = true;
						this.setSlide(this.activeSlide+1);
					},
					interval: this.interval*1000,
					scope: this
				};
				
				this.playTaskBuffer = this.playTaskBuffer || new Ext.util.DelayedTask(function() {
					Ext.TaskMgr.start(this.playTask);
				}, this);
	
				this.playTaskBuffer.delay(this.interval*1000);
				this.playing = true;
				if(this.showPlayButton) {
					if(this.els.navPlay) this.els.navPlay.addClass('ux-carousel-playing');
				}
				this.fireEvent('play');
			}        
			return this;
		},			

		clear: function() {},
		add: function(el, refresh) {},
		
		refresh: function() {
			this.carouselSize = this.slides.length;
			this.els.slidesWrap.setWidth((this.slideWidth * this.carouselSize) + 'px');
			if(this.carouselSize > 0) {
				this.activeSlide = 0;
				this.setSlide(0, true);
			}                
			return this;  		   
		},
		
		setSlide: function(index, initial) {
		
			if(!this.wrap && !this.slides[index]) {
				return;
			}
			else if(this.wrap) {
				if(index < 0) {
					index = this.carouselSize-1;
				}
				else if(index > this.carouselSize-1) {
					index = 0;
				}
			}
			if(!this.slides[index]) {
				return;
			}
	
			if(this.els.caption) this.els.caption.update(this.slides[index].child(':first-child', true).title || '');
			if(typeof TV == 'object') {
				if(typeof this.startSlideFN != 'function') {
					TV.stopVideos();
				}
			}			
			
			var offset = index * this.slideWidth;
			if (!initial) {
				switch (this.transitionType) {
					case 'fade':
						this.slides[index].setOpacity(0);
						this.slides[this.activeSlide].stopFx(false).fadeOut({
							duration: this.transitionDuration / 2,
							callback: function(){
								this.els.slidesWrap.setStyle('left', (-1 * offset) + 'px');
								this.slides[this.activeSlide].setOpacity(1);
								this.slides[index].fadeIn({
									duration: this.transitionDuration / 2
								});
							},
							scope: this
						})
						break;
	
					default:
						var xNew = (-1 * offset) + this.els.container.getX();
						this.els.slidesWrap.stopFx(false);
						this.els.slidesWrap.shift({
							duration: this.transitionDuration / 2,
							x: xNew,
							scope:this,
							callback:function() {
								if(typeof this.startSlideFN == 'function') {
									this.startSlideFN.defer(500,this,[this]);
									this.startSlideFN = false;
								}
							},
							easing: this.transitionEasing
						});
						break;
				}
			}
			else {
				this.els.slidesWrap.setStyle('left', '0');
			}
			
			this.updateBottomNav(index,this.activeSlide);
			this.activeSlide = index;
			this.fireEvent('change', this.slides[index], index);
		},
	
		updateBottomNav: function(i,o) {
			if(this.btnavImgs) {
				if(this.btnavImgs[i]) {
					this.btnavImgs[i].dom.src = '/images/songpier/home-onestop/cl-navi-on.png';
				}
				if(this.btnavImgs[o] && o != i) {
					this.btnavImgs[o].dom.src = '/images/songpier/home-onestop/cl-navi-off.png';
				}
			}		
		}
		
	});
}

