var site_url = location.protocol + '//' + location.hostname;
var cgi_bin = site_url + '/cgi-bin/';
var menuwidth='105px'
var menubgcolor='lightyellow'
var disappeardelay=250
var hidemenu_onclick="yes"
var ie4=document.all
var ns6=document.getElementById&&!document.all
function getposOffset(what,offsettype){var totaloffset=(offsettype=="left")?what.offsetLeft:what.offsetTop;var parentEl=what.offsetParent;while(parentEl!=null){totaloffset=(offsettype=="left")?totaloffset+parentEl.offsetLeft:totaloffset+parentEl.offsetTop;parentEl=parentEl.offsetParent;}
return totaloffset;}
function showhide(obj,e,visible,hidden,menuwidth){if(ie4||ns6)
obj.style.left=obj.style.top="-500px"
if(menuwidth!=""){
obj.style.width=menuwidth
}
if(e.type=="click" && obj.style.visibility==hidden||e.type=="mouseover")
obj.style.visibility=visible
else if(e.type=="click")
obj.style.visibility=hidden}
function iecompattest(){return(document.compatMode&&document.compatMode!="BackCompat")?document.documentElement:document.body}
function clearbrowseredge(obj,whichedge){var edgeoffset=0
if(whichedge=="rightedge"){var windowedge=ie4&&!window.opera?iecompattest().scrollLeft+iecompattest().clientWidth-15:window.pageXOffset+window.innerWidth-15
obj.contentmeasure=obj.offsetWidth
if(windowedge-obj.x<obj.contentmeasure)
edgeoffset=obj.contentmeasure-obj.offsetWidth}
else{var topedge=ie4&&!window.opera?iecompattest().scrollTop:window.pageYOffset
var windowedge=ie4&&!window.opera?iecompattest().scrollTop+iecompattest().clientHeight-15:window.pageYOffset+window.innerHeight-18
obj.contentmeasure=obj.offsetHeight
if(windowedge-obj.y<obj.contentmeasure){edgeoffset=obj.contentmeasure+obj.offsetHeight
if((obj.y-topedge)<obj.contentmeasure)
edgeoffset=obj.y+obj.offsetHeight-topedge}}
return edgeoffset}
function dropdownmenu(obj,e,menucontents,menuwidth){if(window.event)event.cancelBubble=true
else if(e.stopPropagation)e.stopPropagation()
clearhidemenu()
dropmenuobj=document.getElementById ? document.getElementById(menucontents) : dropmenudiv;
if(ie4||ns6){showhide(dropmenuobj,e,"visible","hidden",menuwidth)
dropmenuobj.x=getposOffset(obj,"left")
dropmenuobj.y=getposOffset(obj,"top")

dropmenuobj.style.left=dropmenuobj.x-clearbrowseredge(dropmenuobj,"rightedge")+"px"
dropmenuobj.style.top=dropmenuobj.y-clearbrowseredge(dropmenuobj,"bottomedge")+obj.offsetHeight+"px"}
return clickreturnvalue()}
function clickreturnvalue(){if(ie4||ns6)return false
else return true}
function contains_ns6(a,b){while(b.parentNode)
if((b=b.parentNode)==a)
return true;return false;}
function dynamichide(e){if(ie4&&!dropmenuobj.contains(e.toElement))
delayhidemenu()
else if(ns6&&e.currentTarget!=e.relatedTarget&&!contains_ns6(e.currentTarget,e.relatedTarget))
delayhidemenu()}
function hidemenu(e){if(typeof dropmenuobj!="undefined"){if(ie4||ns6)
dropmenuobj.style.visibility="hidden"}}
function delayhidemenu(){if(ie4||ns6)
delayhide=setTimeout("hidemenu()",disappeardelay)}
function clearhidemenu(){if(typeof delayhide!="undefined")
clearTimeout(delayhide)}
if(hidemenu_onclick=="yes")
document.onclick=hidemenu


/********** Start Common Document Initialization routines *********/
ddaccordion.init({
	headerclass: "teaser_toggle", //Shared CSS class name of headers group
	contentclass: "teaser_toggle_panel", //Shared CSS class name of contents group
	revealtype: "click", //Reveal content when user clicks or onmouseover the header? Valid value: "click" or "mouseover"
	mouseoverdelay: 200, //if revealtype="mouseover", set delay in milliseconds before header expands onMouseover
	collapseprev: true, //Collapse previous content (so only one open at any time)? true/false
	defaultexpanded: [], //index of content(s) open by default [index1, index2, etc]. [] denotes no content.
	onemustopen: false, //Specify whether at least one header should be open always (so never all headers closed)
	animatedefault: true, //Should contents open by default be animated into view?
	persiststate: false, //persist state of opened contents within browser session?
	toggleclass: ["closed_panel", "opened_panel"], //Two CSS classes to be applied to the header when it's collapsed and expanded, respectively ["class1", "class2"]
	togglehtml: ["prefix", "<img src='"+site_url+"/images/dashboard_plus.gif' /> ", "<img src='"+site_url+"/images/dashboard_minus.gif' /> "], //Additional HTML added to the header when it's collapsed and expanded, respectively  ["position", "html1", "html2"] (see docs)
	animatespeed: "fast", //speed of animation: integer in milliseconds (ie: 200), or keywords "fast", "normal", or "slow"
	oninit:function(expandedindices){ //custom code to run when headers have initalized
		//do nothing
	},
	onopenclose:function(header, index, state, isuseractivated){ //custom code to run whenever a header is opened or closed
		if(isuseractivated && state=="block"){			
			$(header).find(".teaser_info2").hide();
		}else{
			$(header).find(".teaser_info2").show();
		}
	}
});

$(function() {
    if($("#codeigniter_profiler").size()>0){
    	$("#codeigniter_profiler").before('<div class="warning_div"><a href="javascript:;" onclick="$(\'#codeigniter_profiler\').show();$(this).parent().remove()">Show profiler</a></div>');
    }
});


/****** Some common vars/ functions *********/
var email_regex=/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;

function course_mark_complete(course_url,obj){
$this=$(obj);
 mark_type=($this.attr("rel")=="complete") ? "1" : "0";
  $.ajax({
	 url : "/my-account/courses/mark_complete/"+course_url+"/"+mark_type,
	 type : "post",
	 success : function(e){
	  if(e=="1"){
	   $.jGrowl("Course completion status changed");
	   if(mark_type==1){
	   	$this.attr("rel","incomplete");
	   	$this.find("img").attr("src",site_url+"images/dashboard_coursesEntry_Butt_markIncomplete.gif");
	   }else{
	   	$this.attr("rel","complete");
	   	$this.find("img").attr("src",site_url+"images/dashboard_coursesEntry_Butt_markCompleted.gif");
	   }
	  }else{
	   $.jGrowl("No change was made");
	  }
	 }
  });
}

function submitRegType(val) {
	if ($('#subscriptionSelected').val() != val) {
		$.ajax({
		  url: 'auth/setRegTypeByPost',
		  type: 'POST',
		  dataType: 'html',
		  data: 'reg_type=' + val + '&ajax=1',
		  success: function(data) {
		    $('#subscriptionData').html(data);
		    $.post(BASE_URL + '/promotion/getPromoPrice', '&b=1', function(info) {
				$('.subsAmount').html(info.price);
			}, 'json');
		  }
		});
	}
}

/*** Add video dialog  ***/
function show_video_browser(url, upload_section)
{
    if(upload_section == undefined || upload_section == null)
    {
        upload_section = '';
    }
   	var w=500;
	var h=300;
	//alert("url:"+url+" sec:"+upload_section);
	
	$.nyroModalManual({
	  titleFromIframe: false,
      type : "content",
      blocker : "document",
      bgColor: '#CCC',
	  width:w,
	  height: h,
	  ajax: {url: url,data: "upload_section="+upload_section,type:"post"}
  });
}

$().ready(function() {
		
	$("input.textfield").focus(function(){
		if ($("input.textfield").val() == "Search") {
			$("input.textfield").val(""); 
			$("input.textfield").css("color", "#000000");
		}
	}).blur(function(){
		if ($("input.textfield").val().replace(/^\s+|\s+$/g,'') == "") {
			$("input.textfield").val("Search"); 
			$("input.textfield").css("color", "#979797");
		}
	});
	
	$(".faqLink").colorbox({innerWidth: 900, innerHeight: 500});
	
	$('#signInLink').click(function(){
		show_sign_in();
	});
	
	$('#feedbackLink').click(function(){
		show_feedback();
	});
	
	$(".contactLink").click(function(){
		show_contact();
	});
	
	$("#userNameMenu").mouseenter(function(){
		$("#helpMenu").hide();
		$("#userMenu").show();		
	});
	
	$(".userHelpMenu").mouseenter(function(){
		$("#userMenu").hide();
		$("#helpMenu").show();
	});
	
	$("#headerMenu").mouseleave(function(){
		$("#helpMenu").hide();
		$("#userMenu").hide();		
	});
	
	$('#pageContent a, a[href$=upload]').click(function() {
		var url = $(this).attr("href");
		var aClass = $(this).attr("class");
		
		if(url) {
			var isUploadVid = /.*\/upload/.test(url);
			if(isUploadVid) {
				url = url + "/";
			}
			var mainPath = url.replace(/http:\/\/[^\/]*(?:\/comments)?/im,"").replace(/\/([^\/]*).*/m, "$1");
			if((!/.*javascript[^$]*/im.test(url)) && (!/.*colorbox.*|.*cboxelement.*/im.test(aClass))) {
				$.ajax({
				   	type: "POST",
				   	url: url,
				  	data: "receiveJSON=true",
					dataType: "json",
				   	success: function(msg){
				     	if (msg.status == 'denied') {
							show_sign_up(mainPath);
						} else if (msg.status == 'basic'){
							if(isUploadVid) {
								show_upgrade_overlay();
							} else {
								location.href = url;
							}
						} else {
							location.href = url;
						}
			  		},
					error: function() {
						location.href = url;
					}
				});
				return false;
			}
		}
	});
	
    activateTab();	

});

function activateTab() {
	var url = location.href;
	var re = new RegExp("(?:my-account|user/[^/]*)/([^/]*)(?:/|$)");
	var matches = re.exec(url);
	if (matches) {
		$('#' + matches[1]).parent().addClass('active');
	}
}

function sendMailForm() {
	$.post("/page/sendContactFeedback", $(".main_block").serialize());
	
	$.nyroModalManual({
		type : "content",
		blocker : "document",
		bgColor: '#000',
		width: 200,
		minHeight: 100,
		showContent: showContentAnimation,
		endShowContent: setFocus,
		ajax: {url: "/page/contact_thank_you", data: "ajax=1", type: "POST"}
	});
	
}

function overlayPopUp(url) {
	$('#upload_video_but').attr('href', 'javascript:;');
	$.ajax({
	   	type: "POST",
	   	url: url,
	  	data: "receiveJSON=true",
		dataType: "json",
	   	success: function(msg){
			if (msg.status == 'basic'){
				show_upgrade_overlay();
			} else {
				location.href = url;
			}
		},
		error: function() {
			location.href = url;
		}
	});
}

function show_upgrade_overlay() {
	var w=420;
	var h=165;
	$.nyroModalManual({
		type : "content",
		blocker : "document",
		bgColor: '#000',
		minHeight: 150,
		width:w,
		height:h,
		showContent: showContentAnimation,
		ajax: {url: "/auth/upgrade_overlay"}
	});
}

function show_sign_in(){
	$.nyroModalManual({
		type : "content",
		blocker : "document",
		bgColor: '#000',
		showContent: showContentAnimation,
		endShowContent: setFocus,
		ajax: {url: "/auth/sign_in"}
	});
	/*When the sign_in loads then the event handler begins*/
	$().keypress(function(event) {
		if(event.keyCode == '13') {
			$(".main_block").submit();
		}
	});
}

function show_feedback(){
	$.nyroModalManual({
		type : "content",
		blocker : "document",
		bgColor: '#000',
		showContent: showContentAnimation,
		endShowContent: setFocus,
		ajax: {url: "/page/feedback"}
	});
}

function show_contact(){
	$.nyroModalManual({
		type : "content",
		blocker : "document",
		bgColor: '#000',
		showContent: showContentAnimation,
		endShowContent: setFocus,
		ajax: {url: "/page/contactNyvs"}
	});
}

/**
 * @author Federico Piagentini
 * @desc This function is called when the Sign_in overlay finishes loading.
 */
function setFocus(elts, settings) {
	$('#email_sign_up').focus();
}
	
function show_sign_up(mainPath){
	$.nyroModalManual({
		type : "content",
		blocker : "document",
		bgColor: '#000',
		minHeight: 150,
		showContent: showContentAnimation,
		ajax: {
			url: "/auth/sign_up",
			data: "href="+mainPath,
			type: "POST"
				}
	});
}

/**
 * 
 * @author Federico Piagentini
 * @desc LOADING ANIMATION for the overlay Pop-ups.
 */
function showContentAnimation(elts, settings, callback) {
  elts.loading
    .css({
      marginTop: '0px',
      marginLeft: settings.marginLeftLoading+'px',
      height: '20px',
	  border: 'none'
    })
    .show()
    .animate
    (
      {
          width: settings.width+'px'
        , marginLeft: settings.marginLeft+'px'
      }
      , 
      {
        duration: 200, 
        complete: function() 
        {
          elts.loading.animate(
            {
                height: settings.height+'px'
              , marginTop: settings.marginTop+'px'
            }
            , 
            {
                duration: 200
              , 
                complete: function() 
                {
                  elts.contentWrapper
                    .css
                    (
                      {
                          width: settings.width+'px'
                        , height: settings.height+'px'
                        , marginTop: settings.marginTop+'px'
                        , marginLeft: settings.marginLeft+'px'
						, border: 'none'
                      }
                    )
                    .show()
                  ;
                  elts.loading.fadeOut(200, callback);
                }
            }
          );
        }
      }
    );
}
