// JavaScript Document
			
//load html content
function lhc(sUrl)
{	
	lastSecureLink = lastglobalMsg = "";

	if(sUrl.indexOf(".html") >=0 || sUrl.indexOf(".aspx")) //sUrl.search(/.aspx|.htm/i)>=0
	{		
		ShowUpdatingProgress(true);
		$(contentAreaID).hide();	
		$.cookie(lastPageCookieKey,sUrl);		
		
		$.get(sUrl,function(data){
			$(contentAreaID).html(data);
			$(contentAreaID).fadeIn('slow');
			ShowUpdatingProgress(false);
		});
		
		$("#statusBar").text(sUrl);
	}
	else
	{
		$(contentAreaID).html(formatError("<b>URL Not supported:</b> \"" + sUrl + "\""));
	}
}

function formatError(msg)
{
	return "<div class='ContentPaddingStyle'><h1 style='color:red'>ERROR:</h1>" + msg + "</div>";
}

function ShowUpdatingProgress(show)
{
	if(show)
		SetAjaxWaitingStatus("Updating content. Please wait...","#UpdateProgress");
	else
		$("#UpdateProgress").text("");
}

function ShowContent(sTarget,show)
{
	var target = document.getElementById(sTarget);
	if(target)
	{
		if(show == true)
			show = "";
		else
			show = "none";
			
		target.style.display = show;		
	}
}

//load homepage content
function lhp()
{
	ShowUpdatingProgress(true);
	lhc('home.html');
	
	var ct = document.getElementById('content_area');
	if(ct)
	{
		ct.style.display = "block";
	}
	
	var cc = document.getElementById('Catalog');
	if(cc)
	{
		cc.style.display = "none";
	}		
	ShowUpdatingProgress(false);
	
	//Reset accordion to none selected
	selectedAccordion = -1;
	$.cookie(selectedAccordionCookieKey,selectedAccordion);
	selectAccordion();
}			

var sCatFilter = "";
function loadCategory(catName)
{
	lhc('category.html');
	//var rgn = Spry.Data.getRegion('CatalogCategory');
    //if (rgn)
	{	
		//SetText('content_area', "DataRegion found: CatalogCategory");
		try
		{
			ShowUpdatingProgress(true);
			
			SetText('SelectedCategory',catName);
			
			sCatFilter = catName;
			dsCategory.setURL("xml/catalog.xml");
			dsCategory.setXPath("Catalog/Categories");
			//,{filterFunc:filterCategory, useCache:true});
			dsCategory.loadData();
			
			//dsCategory.filterData(filterCategory); // Filter the rows in the			
			//Spry.Data.updateRegion('CatalogCategory');
			//rgn.updateRegion();
			
			Spry.Data.initRegions();
			
			//ShowCatalog(true);
			ShowUpdatingProgress(false);
		}
		catch(e)
		{
			alert(e);
		}
	}
	/*else
	{
		SetText('content_area', "DataRegion not found: CatalogCategory");
	}*/
}


var filterCategory = function(dataSet, row, rowNumber)
{
	if (row["ParentName"]!= null && row["ParentName"] != "" && row["ParentName"].search(sCatFilter) >= 0)
		return row; // Return the row to keep it in the data set.
	
	return null; // Return null to remove the row from the data set.
	
}

function SetText(sTarget, text)
{
	var target = document.getElementById(sTarget);
	if(target)
	{
		target.innerHTML = text;
	}
}

function ShowCatalog(show)
{
	ShowContent('Catalog',show);
	ShowContent('content_area',!show);
}


var req;
function retrieveURL(url)
{   
	if(window.XMLHttpRequest)
	{
		req = new XMLHttpRequest();
		req.onreadystatechange =  processStateChange;
		try{
		req.open("GET",url,true);
		}catch(e){ alert(e);}
		req.send(null);
	}else if(window.ActiveXObject)
	{
		req = new ActiveXObject("Microsoft.XMLHTTP");
		if(req)
		{
		   req.onreadystatechange = processStateChange;
           req.open("GET", url, true);
           req.send();
		}
	}
}

function processStateChange()
{
	if(req.readyState == 4)
	{
		if(req.status == 200)
		{			    
			document.getElementById("contentInfo").innerHTML =  req.responseText;
			scroll(0,0);
		}else
		{
			alert("Errors: "+ req.statusText)
		}
	}
}

function ShowInfo(param) 
{
    param = param+"";
    var Html = retrieveURL(param);
}


function MM_openBrWindow(theURL,winName,features) 
{ 
	 window.open(theURL,winName,features);
}


function createVideoPlayer(href, container, width, height)
{
	if(!container)
		container = "#VideoContainer";
	width = width == null ? 371 : width;
	height = height == null ? 350 : height;
	//$("#VideoContainer").html("Loading please wait...");
	//$("#VideoContainer").html(href);

	$.get("fragments/videoplayer.html" + GetCacheBlock(true),function(data){
		data = data.replace(/\$HREF/gi,href);
		data = data.replace(/\$WIDTH/gi,width);
		data = data.replace(/\$HEIGHT/gi,height);
		$(container).html(data);
	});
}

function GetCacheBlock(usequest)
{
	usequest = usequest ? "?cb=" : "&cb=";
	
	return usequest + new Date().getTime();
}
	
function SetAjaxWaitingStatus(msg,targetid)
{
	msg = "<img src='/media/images/ajax/ajax-loader-transp.gif' align='absmiddle'/> " + msg;
	$(targetid).show();
	$(targetid).html(msg);
}

function Authenticate() {
    if (!userLoggedIn) {
        showLoginWindow();
        return false;
    }
    else {
        //InitSecurity();
		var data = userLoggedInData.split(";");
        var name = userFullName = data[2];
        return true;
   }
}

function GetUserID(){
	var data = userLoggedInData.split(";");
	userFullName = data[2];
	return data[0];
}

function InitSecurity() {
    userLoggedInData = $.cookie(userLoggedInCookieKey);
    userLoggedIn = userLoggedInData != null && userLoggedInData != "" ? true : false;
    if (userLoggedIn) {
        userID = GetUserID();
    }
	else
	{
		showLoginWindow();
	}
}

function GetUserLogin(){
	if(userLoggedInData)
	{
		var data = userLoggedInData.split(";");
		return data[1];
	}
	else
	{
		return null;
	}
}

function setUserControl($parentID)
{
	$parentID = $parentID=="" || $parentID == null ? "#contentparent":$parentID;

	$html = "";
	$html += "<div id='profileBar' style='text-align:right;padding-right:20px;'>";
	$html += "<img src='/media/images/icons/icon_user.gif' alignn='absmiddle'/><b>Welcome back: </b><i>";
	$html += userFullName;
	$html += "</i> | <a id='cmdLogout' href='#'>Logout</a><!-- | <a id='cmdEditProfile' href='#'>Edit My Account</a>-->";
	$html += "</div>";

	$($parentID).prepend($html);
	$("#cmdLogout").click(function()
	{
		//console.log($USER_COOKIE);
		$.cookie($USER_COOKIE,null,{ path: '/', expires: 10 });
		//alert("You have been logged out");
		window.location.reload();
		return true;
	});
}

function showLoginWindow() {
    var dOffset = $('#loginForm').offset();
	$.get("/fragments/login.html",function($data){
		$("body").append($data);

		$("#loginForm #login,#loginForm #password").keypress(function(event){
			if (event.keyCode == 13) {
				//alert('enter pressed!');
				isUserValid();
			}
		});

		$('#loginForm').dialog({
			modal: true,
			overlay: { opacity: 0.7, background: "black" },
			width: 375,
			height: 275,
			buttons: {
				'Login': function() {
					isUserValid();
				},
				'Cancel': function() {
					window.location = "/";
					return false;
					//$(this).dialog("close");
					//if(securecontent!=null && securecontent!="")
					{
						var html = "";
						html += "<div id='loginreqpanel'>";
						html += "<h2>";
						html += "<img src='/media/images/icons/icon_lock.png' align='absmiddle'/>";
						html += "Authentication Required.</h2>";
						html += "You need to login to use this page completely. If you are not registered please obtain a registration.";
						html += "<br/><br/>";
						//html += "<input type='button' id='calllogin' value='Login'/>";
						//html += "<input type='button' id='callregister' value='Register'/>";
						html += "</div>";
						$("body").append(html);
						$("#loginreqpanel").dialog({
							modal:true,
							overlay:{opacity:0.7, background:"black"},
							width: 375,
							height: 275,
							buttons:
								{	
									'Login':function(){
										$(this).dialog("destroy").remove();
										InitSecurity();
										//$("#calllogin").click(function(){InitSecurity();});		
										//$("#callregister").click(function(){document.location = "dealerregister.html";});
									},
									'Cancel':function(){
										window.location = "/";
									}							
								}
						});
						
						//$(securecontent).fadeIn();
					}
				}
			}
		});
		window.scrollTo(0, 0);	
	});
}

function isUserValid() {
	try
	{
		var errors = "";
		$(':input.required').trigger('blur');
		if (errors != "") {
			$("#errors").html("<h2 class='error'>Please correctly fill in all highlighted fields.</h2>");
			return false;
		}
		else {
			if ($("#login").val() != "" && $("#password").val() != "") {

				SetAjaxWaitingStatus("Authenticating. Please wait...","#errors");

				var postData = $("#loginForm :input").serialize() + GetCacheBlock();
				$.post("/code/login.aspx", postData, function(data) {

					if (data.search(/pending|exists|failed|commands/i) >= 0) {
						$("#errors").html(data);
						return false;
					}
					else {
						$.cookie(userLoggedInCookieKey, data);
						Authenticate();
						window.location.reload();
					}
				});
			}
			else {
				$("#errors").html("Please fill in all fields.");
				return false;
			}
		}		
	}
	catch (err)
	{
		alert("Error occured\n" + err.description );
	}
}

function ajaxFileUpload(callback, filename, dimensions, selector, elementID)
{
	$("#loading").ajaxStart(function(){
		$(this).show();
	}).ajaxComplete(function(){
		$(this).hide();
	});

	elementID = elementID != "" ? elementID : "fileToUpload";
	$.ajaxFileUpload
	(
		{
		    url: '/code/ajaxfileupload.aspx' + GetCacheBlock(true) + uidQS + '&fn=' + filename + '&dim=' + dimensions,
		    secureuri: false,
		    fileElementId: elementID,
		    selector: selector,
		    dataType: 'json',
		    success: function(data, status) {
		        if (typeof (data.error) != 'undefined') {
		            if (data.error != '') {
		                alert(data.error);
		            } else {
		                if (callback != null) {
		                    callback.invoke();
		                }

		                if (data.msg != '') {
		                    alert(data.msg);
		                }
		            }
		        }
		    },
		    error: function(data, status, e) {
		        alert("Here in return:" + e);
		    }
		}
	)	
	return false;
}


function popup($file,$width,$height,$title)
{
	tb_show($title, $file + "?width="+$width+"&height="+$height);
}
