var ie = document.all != null;
var mz = !ie && document.getElementById!= null ;// && document.layers == null;
var mac = (navigator.platform.indexOf('Mac') >= 0);

function postStats(){
	if(getCookie('stats') != 'saved'){
		try{
		getResponse('/stats.update/?screenWidth='+screen.width+'&screenHeight='+screen.height);
		expDate = new Date();
		expDate = new Date(expDate.getTime()+1000*60*60*24);
		setCookie('stats', 'saved', expDate);
		}catch(e){}
	}
}

postStats();

function setCookie(name, value, expires){
    document.cookie= name + "=" + escape(value) + ((expires) ? "; expires=" + expires.toGMTString() : "");
}

function getCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1){
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else{
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1){
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

function deleteCookie(name, path, domain){
    if (getCookie(name)){
        document.cookie = name + "=" + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") +           "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}


function openPhotoManager() {
	window.open('/photo/profile/', 'drphilphoto', 'height=465,width=720,resize=true');
}

String.prototype.trim = function() {
	var r = /^\s+|\s+$/;
	var a = this.split(/\n/g),
	i=a.length;
	while(i-->0){
		a[i]=a[i].replace(r,'');
	}
	return a.join('\n');
}

function toggle(containerID) {
	var container = document.getElementById(containerID);
	if(container) {
		container.style.display = (container.style.display == 'none') ? 'block' : 'none';
		return(container.style.display);
	}
	return(0);
}

function toggleOn(containerID) {
	var container = document.getElementById(containerID);
	if(container) {
		container.style.display = 'block';
	}
	return(0);
}

function toggleOff(containerID) {
	var container = document.getElementById(containerID);
	if(container) {
		container.style.display = 'none';
	}
	return(0);
}


function toggleInl(containerID) {
	var container = document.getElementById(containerID);
	if(container)
		container.style.display = (container.style.display == 'none') ? 'inline' : 'none';
}

function checkRequired(myElements) {
	for(element in myElements) {
		if(myElements[element].value.trim() == '') {
			alert('Error: [' + ((myElements[element].title) ? myElements[element].title : myElements[element].name) + '] is a required field.');
			if(myElements[element].type != 'hidden')
				myElements[element].focus();
			return(false);
		}
	}
	return(true);
}

// don't put unnesessary scripts here

function showSmallPop(url,name) {
	alert('deprecated!');
	options = "toolbar=no,status=no,menubar=no,scrollbars=no,resizable=no,width=470,height=550";
	newwindow=window.open(url,name, options);
	newwindow.document.close();
	window.name='phil_main';
}

function slideshow(myID,myXML) {
	var href = window.location.href.split('/');
	var showID = 0;
	if( (href[3] == 'shows') &&
		(href[4] == 'show') ) {
		showID = href[5];
	}

	var pos = 0;
	var extra = (window.location.href.indexOf('preview=1') > 0) ? '&preview=1' : '';
	pos = window.location.href.indexOf('versionID=');
	var extra2 = (pos > 0) ? ('&versionID=' + ((window.location.href.substring(pos + 10, pos + 11)))) : '';

	window.location.href = '/slideshows/slideshow/' + myID +'/?id=' + myID + '&showID=' + showID + extra + extra2;
}

function tip(myID,myXML) {
	slideshow(myID,myXML, 'isTip');
}

function poll(myID) {
	var myOptions = 'toolbar=no,status=no,menubar=no,scrollbars=no,resizable=no,width=470,height=550';
	newwindow = window.open('/polls/poll/' + myID + '/', 'poll', myOptions);
}

function popup(URL, w, h, options) {
	if(!options) options = 'toolbar=0,menubar=0,status=1,locationbar=no,scrollbars=0,resizable=yes,top=100,left=100';
	if(!w) w = 505;
	if(!h) h= 485;
	aWindow = window.open(URL, 'newWin', 'width='+w+',height='+h+','+options);
}

function drphilstore(){
	window.open("http://www.drphilstore.com/", "DrPhilStore", "");
}

function tapesandtranscripts(){
	popup('http://tapesandtranscripts.drphil.com', 530, 490, 'toolbar=0,menubar=0,status=1,locationbar=no,scrollbars=1,resizable=yes,top=100,left=100');
}

function validateEmail(str){
	var emailRegEx = /^[a-z0-9\._&-]+@+[a-z0-9\._-]+\.+[a-z]{2,6}$/;
//	var emailRegEx = /^[a-zA-Z0-9][\w\._-]@[a-zA-Z0-9][\w\._-]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;
	return (emailRegEx.test(str.toLowerCase()));
}

function countDown(tick) {
	if (tick == 0) {
		if(confirm('You are about to be logged out due to inactivity. Clicking OK will keep you logged in. Clicking Cancel or not responding will log you out.')) {
			countDown(5400);
		} else {
			location.href='/members/logout/';
		}
		return;
	}
	var time = "Time remaining till you are automatically logged out. ";
	var minute = Math.floor(tick / 60);
	if (minute < 10) {
		time += "0";
	}
	time += minute + ":";
	var second = tick % 60;
	if (second < 10) {
		time += "0";
	}
	time += second;
//	window.status = time;
	--tick;
	var command = "countDown(" + tick + ")";
	window.setTimeout(command,1000);
}

function SymError(err){
//	alert(err);
 	return true;
}

//window.onerror = SymError;

//-----------------------------------------------------------
function startList() {
	if (document.getElementById) {
		navRoot = document.getElementById('menu');
		for (i = 0; i < navRoot.childNodes.length; i++) {
			node = navRoot.childNodes[i];
			if (node.nodeName == 'LI') {
				node.onmouseover = function() {
					this.className += ' over';
				}
				node.onmouseout = function() {
					this.className = this.className.replace(' over', '');
					//setTimeout('HideAllOver();', 500);
				}
			}
		}
	}
}

function HideAllOver() {
	var E = GetElementsByClassName(document.getElementById('Menu'), 'LI', 'base over');
	for (var i = 0; i < E.length; i++) {
		E[i].className = E[i].className.replace(' over', '');
		return;
	}
}
//-----------------------------------------------------------

function GetElementsByClassName(MyContainer, MyTagName, MyClassName) {
	var MyElements = new Array();
	if (MyContainer) {
		var MyTags = MyContainer.getElementsByTagName(MyTagName);
		for (var w = 0; w < MyTags.length; w++) {
			if(MyTags[w].className.match(new RegExp("(^|\\s)" + MyClassName + "(\\s|$)")))
				MyElements.push(MyTags[w]);
		}
	}
	return MyElements;
}

// Debug ----------------------------------------------------
function Debug(MyObject) {
	var MyHeader  = '//VPI_JS_Debug-----------------------------------------------' + "\n";
		MyHeader += (MyObject['tagName'] ? 'Tag Name: ' + MyObject['tagName'] + "\n" : '');
		MyHeader += 'Type: ' + (typeof MyObject) + "\n";
	var MyFooter  = "\n\n" + '//----------------------------------------------------------------';
	var z = 0;
	var y = 0;
	var MySplit = 'Page [' + ++y + ']' + "\n" + '//----------------------------------------------------------------' + "\n\n";
	var MyMessage = '';
	for(var i in MyObject) {
		MyMessage += '[' + i + '] -> ' + MyObject[i] + "\n";
		if(z++ > 15) {
			alert(MyHeader + MySplit + MyMessage + MyFooter);
			z = 0;
			MySplit = 'Page [' + ++y + ']' + "\n" + '//----------------------------------------------------------------' + "\n\n";
			MyMessage = '';
		}
	}
	alert(MyHeader + MySplit + MyMessage + MyFooter);
}
//-----------------------------------------------------------

//------------------------------------------------------[TG]
function Populate(Data) {
	return false;

	var Data = eval('(' + unescape(Data.substr(0, Data.indexOf('=&onLoad=', ''))) + ')');

	return;

	alert(Data);
	Debug(Data);

	if (!Data['id']) return;

	if (Data['birthday'])
		Data['birthday'] = Data['birthday'].split('-');

	document.getElementById('30').value = Data['firstname'];
	document.getElementById('31').value = Data['lastname'];

	var Year = document.getElementById('birthYear');
	for (var i = 0; i < Year.options.length; i++) {
		if (Year.options[i].value == parseInt(Data['birthday'][0])) {
			Year.selectedIndex = i;
			break;
		}
	}
	var Month = document.getElementById('birthMonth');
	for (var i = 0; i < Month.options.length; i++) {
		if (Month.options[i].value == parseInt(Data['birthday'][1])) {
			Month.selectedIndex = i;
			break;
		}
	}
	var Day = document.getElementById('birthDay');
	for (var i = 0; i < Day.options.length; i++) {
		if (Day.options[i].value == parseInt(Data['birthday'][2])) {
			Day.selectedIndex = i;
			break;
		}
	}

	document.getElementById('33').value = Data['email'];

	document.getElementById('34').value = Data['address1'] + ' ' + Data['address2'];
	document.getElementById('35').value = Data['city'];

//	document.getElementById('36').value = Data['state']; // State

	document.getElementById('38').value = Data['zipcode'];
	document.getElementById('40').value = Data['phone'];
	document.getElementById('48').value = Data['cell'];

}
//------------------------------------------------------[TG]

// Change Video ----------------------------------------[TN]
changeVideo = function(videoID) {
	var type 	= (arguments[1]) ? arguments[1] : false;
	var anchor 	= (arguments[2] != null) ? arguments[2] : true;
	var preRoll = (arguments[3] != null) ? arguments[3] : false;
	if (videoID) {
		$.get('/video_info/', {videoID: videoID, type: type}, function(data) {
			if (data.success) {
				params = {
					quality: 'high',
					allowFullScreen:	'true',
					allowScriptAccess: 'always',
					allowNetworking:	'all',
					movie: ((preRoll) ? 'http://r.unicornmedia.com/content.aspx?uid=AC26FE85-334B-4A21-B72C-154F743F5739&at=3dcb488e-4b58-41b6-b4a4-da84932adf78' : 'http://r.unicornmedia.com/content.aspx?uid=AC26FE85-334B-4A21-B72C-154F743F5739&at=b5e7a882-5843-4a1c-826f-6cfe313896fa')
				};
				if (data.h264_browser && data.h264_video != '') {
					$('#VideoPlayer').html('<video width="540" height="344" controls></video>');
					$('#VideoPlayer').children('video').attr('src', data.h264_video);
					$('#VideoPlayer').children('video').get(0).play();
				} else if (data.flv_video_guid != '' && (enableUnicorn == undefined || enableUnicorn)) {
					flashvars = {config: ((preRoll) ? 'http://r.unicornmedia.com/embed/3dcb488e-4b58-41b6-b4a4-da84932adf78?view=item%26view_id=' : 'http://r.unicornmedia.com/embed/b5e7a882-5843-4a1c-826f-6cfe313896fa?view=item%26view_id=') + data.flv_video_guid};
					swfobject.embedSWF(((preRoll) ? 'http://r.unicornmedia.com/content.aspx?uid=AC26FE85-334B-4A21-B72C-154F743F5739&at=3dcb488e-4b58-41b6-b4a4-da84932adf78' : 'http://r.unicornmedia.com/content.aspx?uid=AC26FE85-334B-4A21-B72C-154F743F5739&at=b5e7a882-5843-4a1c-826f-6cfe313896fa'), 'VideoPlayer', '540', '344', '8', '/swf/express_install.swf', flashvars, params);
				} else {
					flashvars = {file:data.flv_video,autostart:true};
					swfobject.embedSWF('/swf/player.swf',(($('#jwplayer').length) ? 'jwplayer' : 'VideoPlayer'),'540','344','9.0.115','false', flashvars, params, { id:'jwplayer', name:'jwplayer' });
				}

				if (anchor)
					location.href = '#VideoPlayer';
			}
		}, 'json')
	}
	return(false);
};
//------------------------------------------------------[TN]
// Video Overlay ---------------------------------------[TN]
overlayVideo = function(videoID) {
	var type 	= ((arguments[1]) ? arguments[1] : false),
		width = ((arguments[2]) ? arguments[2] : 540),
		height = ((arguments[3]) ? arguments[3] : 'auto');
	if (videoID) {
		$.get('/video_info/', {videoID: videoID, type: type}, function(data) {
			if (data.success) {
				if (!$('#popvideo').length) {
					$('body').append('<div id="popvideo"><iframe name="overlayframe" id="overlayframe" width="540" height="400" src="/overlay/" scrolling="no" frameborder="0" allowtransparency="true"></iframe></div>');
				}
				params = {
					quality: 'high',
					allowFullScreen:	'true',
					allowScriptAccess: 'always',
					allowNetworking:	'all',
					movie: 'http://r.unicornmedia.com/content.aspx?uid=AC26FE85-334B-4A21-B72C-154F743F5739&at=b5e7a882-5843-4a1c-826f-6cfe313896fa'
				};
				if (data.h264_browser && data.h264_video != '') {
					if ($('video').length) {
						$('video').get(0).pause();
					}
					$('#overlayframe').attr('src', '/overlay/?h264_video=' + data.h264_video);
				} else if (data.flv_video_guid != '' && (enableUnicorn)) {
					$('#overlayframe').attr('src', '/overlay/?flv_video_guid=' + data.flv_video_guid);
				} else {
					$('#overlayframe').attr('src', '/overlay/?flv_video=' + data.flv_video);
				}

				var playerIds = ['VideoPlayer', 'mainplayer', 'jwplayer'];
				for (var i=0; i<playerIds.length; i++) {
					if ($('#' + playerIds[i] + ':visible').length && $.trim($('#' + playerIds[i] + ':visible').html()) !== '') {
						if ($('#' + playerIds[i] + ':visible').attr('name') === undefined && $('#' + playerIds[i] + ':visible').attr('name') !== playerIds[i]) {
							um.pause(playerIds[i]);
						}

						if (jwplayer(playerIds[i]).getState() !== 'PAUSED' && jwplayer(playerIds[i]).getState() !== undefined) {
							jwplayer(playerIds[i]).pause();

						}
					}
				}
				$('#popvideo').dialog({ width: width, height: height, modal: true, beforeClose: function() {
					$('#popvideo').remove();
				}});
			}
		}, 'json')
	}
};
//------------------------------------------------------[TN]



function PopVideo( MyURL ) {
	var Height = 344;
	var Width = 540;

	if(Height > screen.height)
		Height = screen.height;
	if(Width > screen.width)
		Width = screen.width;

	if (!$('#popvideo').length) {
		$('body').append('<div id="popvideo" style="width: (' + Width + '); height: (' + Height + ');"><iframe src="/videos/?width=' + Width + '&height=' + Height + '&' + ( ( MyURL ) ? 'Url=' + MyURL : '' ) + '" width="' + (Width) + '" height="' + (Height) + '" scrolling="no" frameborder="0"></iframe></div>');
	}

	$('#popvideo').dialog({ width: Width, height: Height, modal: true, beforeClose: function() {
		$('#popvideo').remove();
	}});

	return(false);
}

