// JavaScript Document
var myModal, rightLogoutInit = $empty, 
	loginUser = function(u){ 
	    var topRewrite = '<label id="right_user_log_name_label">Hi '+u+'!</label><a href="http://www.healthguru.com/user/myprofile\">My Account</a><a href="http://www.healthguru.com/user/profile/view/'+u+'">My Profile</a><a id="right_user_log_out" href="/user/logout">Logout</a>';
	    if($('right_user_login_line')) {
		    $('right_user_login_line').set('html', topRewrite);			
			//rightLogoutInit();
	    }
	};

var channelColor = {'sex':'#ff0000','pregnancy':'#fe93bd','college':'#2210d2','www':'#fda100'};	
	
window.addEvent('domready', function()
{
  if($('search_text') !== null)
  {
    $('search_text').addEvents({
      'focus': function(){
        if(this.value == "SEARCH") {
            this.value = "";
        }
        this.setStyle('color','#000000');
      },
      'blur': function(){
       if(this.value.length <= 0)
       {
          this.value = "SEARCH";
          this.setStyle('color','#97AABF');
       }
      }
    });
  }
  
  if($('email_text') !== null)
  {
    $('email_text').addEvents({
      'focus': function(){
        this.value = "";
        this.setStyle('color','#000000');
      },
      'blur': function(){
       if(this.value.length <= 0)
       {
          this.value = "EMAIL ADDRESS";
          this.setStyle('color','#97AABF');
       }
      }
    });
  }
  
  if($('actualcrumb')) {
  	$('actualcrumb').getLast('a').erase('href');
  }
  
  rightLogoutInit = function() {
    $('right_user_log_out').addEvent('click', function(e) {
        e.stop();
        
        var logLineHolder = $('right_user_login_line');
        var logMorph = new Fx.Morph(logLineHolder);
        var logOut = new Request({
          url:'/ajax/userlogout/',
          onSuccess:function(txt){
          		var loc = window.location.href;
          		if(loc.indexOf("#") > 0)
          			loc = loc.substring(0,loc.indexOf("#"));
                window.location.href=loc;
            }
          });
          
          logMorph.start({'opacity':0}).chain(function(){
            logLineHolder.set('html', 'Logging User Out');
                logMorph.start({'opacity':1}).chain(function(){
                    logOut.send();
                });
          });
          
    });  	
  }
    if($('right_user_log_out'))
    {
    	//rightLogoutInit();
    }
    
  if($$('.calendar_input').length > 0) {
  	initCalendars();
  }

	if($('login_button')) {
	  if(Browser.Engine.trident) 
		  return 0;
		$('login_button').addEvent('click',function(e){
			e.stop();
			var myRequest = new Request({method: 'get', url: '/ajax/login'}).send();
			myRequest.onSuccess = function(response){
				myModal = new Modal({speed:200}).addEvent('onShow',function(){
					initLogin();
				});
				myModal.show(response,{
					transparent:true,
					close:'<img src="/css/'+channelName+'/i/login/PHG_CloseX.png" />',
					closeCoords:'10px 380px',
					height:'215px'
				});
			}
		});
	}
	
	$$('.login_button').addEvent('click',function(e){
		e.stop();
		$('login_button').fireEvent('click',e);
	});
	
	// Ads Click INit remove after openX intigrated
	/*if($('right_squaread_box')) {
		$('right_squaread_box').addEvent('click',function(){
			location.href="http://www.sexhealthguru.com";
		});
	}*/	
	//End Ads
	
	//Video Play Button
/*	if($('container')) {
		var playButton = new Element('img',{ 
			src:'/css/i/PlayButtonRolledOver100x75.png',
			styles:{
				'opacity':0,
				'position':'absolute',
				'cursor':'pointer'
			} 
		}).injectInside('container'),
			videoThumbs = $$('img.video_thumb'),
			videoThumbFx,videoThumbLeft = false;
	    
	    videoThumbs.addEvents({
	        'mouseenter':function(){
	        	if($chk(videoThumbFx))
	        		videoThumbFx.destroy();
	        	videoThumbFx = playButton.clone()
	        		.addEvent('mouseleave',function(){
			        	this.morph({'opacity':0});
			        	(function(){this.destroy();}).bind(this).delay(500);
	        		})
	        		.injectBefore(this)
	            	.morph({'opacity':[0,1]});
	        }
	    });
	}
	*/
	$$('a.forgot_link').removeEvents().addEvent('click',function(e){
		e.stop();
		initForgotLinks();
	});

	//AdZone Checker
/*	$$('#header_ad_banner', '#right_squaread_box').addEvent('domready',function(){
		var adTxt = this.get('text');
		if(adTxt.indexOf('OA_show') != -1) {
			var adLen = adTxt.length;
			if(adLen <= 60)
				alert(adLen + adTxt);
		}
	}); */
	
	if(!Cookie.read('leftNavFx'))
		breadcrumbFx();	
	
	if( ($$('embed[src*=/mediauri/').length > 0) && (location.href.indexOf('/content/video') == -1) )
		fireBeacon();
		
	if($('search_text')) {
	    new Autocompleter.Request.JSON('search_text', '/ajax/suggestions', {
	        'postVar': 'search'
	    });	
	}
});

var logos, myTips;
function breadcrumbFx(){
	logos = $$("#breadcrumb #logo_block .channelLogo img");
	logos.removeEvents().addEvents({
		'domready':function(){		
			this.set('morph',{duration:200});				
		},
		'mouseenter':function(){
			var id=this.get('id').substring(13),
				logo = this;
			this.morph({"width":"30px", "height":"30px"});
			(function(){logo.set('src',$('logo_src_big_'+id).get('value'))}).delay(100);
			
		}, 
		'mouseleave':function(){
			var id=this.get('id').substring(13),
				logo = this;
			this.morph({"width":"20", "height":"20"});
			(function(){logo.set('src',$('logo_src_small_'+id).get('value'))}).delay(200);
		}
	});

	myTips = new Tips($$('.toolTips'), {className:'toolTips'});
}

function disableBreadCrumbFx()
{
	myTips.detach('.toolTips');
	logos.removeEvents();
}

var initForgotLinks = function() {
	var myRequest = new Request({method: 'get', url: '/ajax/forgotpassword'}).send();
	myRequest.onSuccess = function(response){
		myModal = new Modal({speed:200}).addEvent('onShow',function(){
			initRecover();
		});
		myModal.show(response,{
			transparent:true,
			close:'<img src="/css/'+channelName+'/i/login/PHG_CloseX.png" />',
			closeCoords:'10px 380px',
			height:'215px'
		});
		initRecover();	
	}		    	
	
}


function initLogin() {
    var usernameBox = $('login_username');
    var passBox = $('login_password');
    var passText = $('password_overlay');
    var forgotPass = $('forgotten_password');

    usernameBox.addEvents({
        'focus':function(){
            this.value = '';
            this.setStyle('color', '#000000');
        },
        'blur':function(){
            if(this.value.length == 0) {
                this.value = 'USERNAME';
                this.setStyle('color', '#98AABE');
            }
        }
    });
    
    passBox.addEvents({
        'focus':function(){
            this.value = '';
            this.setStyle('color', '#000000');
            this.setStyle('text-align', 'left');
            passText.setStyle('display', 'none');
        },
        'blur':function(){
            if(this.value.length == 0){
                passText.setStyle('display', 'block');
            }
        }
    });      
    
    passText.addEvent('click', function(){
        passBox.focus();
    });  
/*    
    forgotPass.addEvent('click', function(e){
		e.stop();
		if($('forgotpass_block').get('html') == '') {
			var myRequest = new Request({method: 'get', url: '/ajax/forgotpassword'}).send();
			myRequest.onSuccess = function(response){
				//myModal.updateContent(response);
				$('forgotpass_block').set('html',response);	
				initRecover();	
			}		    	
		} else {
			$('forgotpass_block').set('html','');	
		}
    });
    
	$('loginForm').addEvent('submit', function(e) {
		e.stop();
		$('login_message').set('html','<img id="loadIcon" src="/css/'+channelName+'/i/load.gif">');
		this.set('send', {onComplete: function(response) { 
			myModal.updateContent(response);
			if(response.indexOf('LOGGED IN')>=0)
				(function(){
              		var loc = window.location.href;
              		if(loc.indexOf("#") > 0)
              			loc = loc.substring(0,loc.indexOf("#"));
	                window.location.href=loc;						
				}).delay(3000);
			else
				initLogin();
		}});
		this.send();
	});           
*/
}

function initRecover() {
	var emailBox = $('float_email');	
    emailBox.addEvents({
        'focus':function(){
            this.value = '';
            this.setStyle('color', '#000000');
            this.setStyle('text-align', 'left');
        },
        'blur':function(){
            if(this.value.length == 0) {
                this.setStyle('color', '#98AABE');
                this.value = 'EMAIL';
            }
        },
        'domready':function(){
            if(this.value.length == 0) {
                this.setStyle('color', '#98AABE');
                this.value = 'EMAIL';
            }
        }
    });

/*	
	$('recoverForm').addEvent('submit', function(e) {
		e.stop();
		$('response_message').set('html','<img src="/css/'+channelName+'/i/load.gif">');
		this.set('send', {onComplete: function(response) { 
			if(!$('forgotpass_block')) {
				myModal.updateContent(response);
				$('recover_box_holder').addClass('solid_border');
			} else
				$('forgotpass_block').set('html',response);	
			initRecover();
		}});
		this.send();
	});  */            		
}

function initCalendars() {
	$each($$('.calendar_input'),function(o,i){
		var inputId,inputFormat,showTime;
		if(o.get('type') != 'text')
			o = o.getElement('input[type=text]');
		if(o.hasClass('date')) {
			inputFormat = "%Y-%m-%d";
			showTime = false;
		} else {
			inputFormat = "%Y-%m-%d %H:%M:%S";			
			showTime = true;
		}
		Calendar.setup({
			inputField  : o,         // ID of the input field
			ifFormat    : inputFormat,    // the date format
			button      : inputId,
			showsTime : showTime
		}); 		
	});
}

function fireBeacon() {	
	// New Fullturn Beacon.
	$("img1").set('src', "http://beacon.securestudies.com/scripts/beacon.dll?C1=1&C2=3000021&C3=&C4=&C5=&C6=&C7=" + escape(window.location.href) + "&C8=" + escape(document.title) + "&C9=" + escape(document.referrer) + "&rn=" + Math.floor(Math.random()*99999999));		
	
	//Original Beacon Snippet, using old C2 code for use with a different FullTurn Media account.
	//$("img1").set('src', "http://beacon.securestudies.com/scripts/beacon.dll?C1=1&C2=6035213&C3=&C4=&C5=&C6=&C7=" + escape(window.location.href) + "&C8=" + escape(document.title) + "&C9=" + escape(document.referrer) + "&rn=" + Math.floor(Math.random()*99999999));		
	
	//alert('Beacon fired');
}

var loadJS = function(file) { 
	var script = new Element('script',{
		'src':file,
		'type':'text/javascript'
	}).inject($$('head')[0]); 
},
	talkBox = {
		init : function() {
			alert($('container').get('html'));
			$('container').append(new Element('div',{'id':'myTalkBox'}));
			$('myTalkBox').set('html','<div class="notice_bubble_right_top"></div><div class="notice_bubble_right_mid"></div><div class="notice_bubble_right_btm"></div>');
		},
		show : function(localizer, msg, shiftX, shiftY) {
			if(!$('myTalkBox'))
				this.init();
			shiftX = $pick(shiftX,50);
			shiftY = $pick(shiftY,0);
		    $('myTalkBox').getElement('notice_bubble_right_mid').set('html', msg);
			var h = $('myTalkBox').getCoordinates().height;
		    $('myTalkBox').setStyles({'top':(localizer.getPosition().y-h+shiftY)+'px', 'left':(localizer.getPosition().x+shiftX)+'px', 'opacity':0, 'visibility':'visible'});
		    $('myTalkBox').fade(1);
		},
		hide : function() {
	    	$('myTalkBox').fade(0);	
		}
	};
	
//	talkBox.show($('upload_picture'),'asdsa');


var tooltip = {
	show : function(localizer, text, shiftX, shiftY) {
		shiftX = $pick(shiftX,50);
		shiftY = $pick(shiftY,0);
	    $('tooltip_mid').set('html', text);
		var h = $('tooltip').getCoordinates().height;
	    $('tooltip').setStyles({'top':(localizer.getPosition().y-h+shiftY)+'px', 'left':(localizer.getPosition().x+shiftX)+'px', 'opacity':0, 'visibility':'visible'});
	    $('tooltip').fade(1);
	},
	hide : function() {
	    $('tooltip').fade(0);	
	}
};	


function $get(key,url){
	if(arguments.length < 2) url =location.href;
	if(arguments.length > 0 && key != ""){
		if(key == "#"){
			var regex = new RegExp("[#]([^$]*)");
		} else if(key == "?"){
			var regex = new RegExp("[?]([^#$]*)");
		} else {
			var regex = new RegExp("[?&]"+key+"=([^&#]*)");
		}
		var results = regex.exec(url);
		return (results == null )? "" : results[1];
	} else {
		url = url.split("?");
		var results = {};
			if(url.length > 1){
				url = url[1].split("#");
				if(url.length > 1) results["hash"] = url[1];
				url[0].split("&").each(function(item,index){
					item = item.split("=");
					results[item[0]] = item[1];
				});
			}
		return results;
	}
}