﻿var sURL = unescape(window.location.pathname);
var SESSION_TIMEOUT = 1805000;

var SERVICES_TAB_INDEX = 1;
var HOME_TAB_INDEX = 0;

var WATCHLIST_TAB_INDEX = 2;
var SAMPLES_TAB_INDEX = 0;
var WATCHLIST_ID_COL = 0;
var WATCHLIST_SERIAL_COL = 1;
var LoggedIn;

var returnUrl = "";

//load components, and add event listeners
function init(loggedin)
{
    loggedin? LoggedIn = true : LoggedIn = false;
    nitobi.html.Css.precacheImages();
    nitobi.loadComponent('mainTabs');
    if (loggedin)
        setTimeout("SessionLoop()", SESSION_TIMEOUT);
        
    document.observe('lightview:opened', function(event) {
        SetFlashVisibilityCss("hidden");
    });            
    
    document.observe('lightview:hidden', function(event) {
        SetFlashVisibilityCss("visible");
    });      
	
    
}

//hide/show the login form at the top of the winow
function ToggleLogin()
{
    if ($("login").style.display != "none")
    {
        Effect.BlindLeft("login");   
    }
    else
    {
        Effect.BlindRight("login");   
    }
}

// show the trademark details lightbox
// evtArgs is an event object passed from the grid
function showDetails(evtArgs)
{
    if (!LoggedIn)
    {
        loginLightBox(true);    
    }
    else if (evtArgs)
    {
        var grid = evtArgs.getSource();
        var row = evtArgs.cell.getRow();
        var serial = grid.getCellObject(row,WATCHLIST_SERIAL_COL).getValue();
        var id = grid.getCellObject(row,WATCHLIST_ID_COL).getValue();
        //var lvWidth = (0.9*document.documentElement.clientWidth > 1200)? 1200 : parseInt(0.9*document.documentElement.clientWidth);
        
        Lightview.show({ href: 'Details.aspx?serial='+serial+'&id='+id, rel: 'iframe', title:'Trademark Details', options: { width: 800, height: 550}});
    }
    else
        Lightview.show({ href: 'Details.aspx', rel: 'iframe', title:'Trademark Details', options: { width: 1200, height: 800}});
    
}

// show the help in a lightbox
var url;
function ShowHelp(page)
{
    /*url = "help.htm#" + anchor;
    document.observe('lightview:opened', function(event) {
        document.getElementById('lightviewContent').contentWindow.document.getElementById(anchor).scrollTo();
    });*/	
    Lightview.show({ href: "help/" + page, rel: 'iframe', title:'Help', options: { width: 600, height: 600}});
}

//ping server/session.ashx to see if the session has expired. if so, prompt to log back in
function SessionLoop()
{
    var xhr = new nitobi.ajax.HttpRequest();
    xhr.handler = "server/session.ashx";
    xhr.async = true; // async is true by default
    xhr.responseType = "text"; // by default the appropriate responseType will be used - ie XML if the data is valid XML otherwise "text".
    xhr.onGetComplete.subscribeOnce(function(evtArgs) {
            //if the session is expired, have the user log in again
            //otherwise, the session is still active, or the request failed, so just reset the loop
            if (evtArgs.response == "expired")
                loginLightBox(false);
            else
            {
                //session timeout is set to 1 min on server, so wait a little longer
                //can't ping every 10 s because these requests themselves keep the session aliveS
                setTimeout("SessionLoop()",SESSION_TIMEOUT);
            }                    
        });
    xhr.get();
}

//adds the state of the tabstrips to the querystring so that this can be reloaded when a login or signup occurs
function StateQueryString()
{
    var querystring = "";
    var servicetab;
    var mainTabstrip = nitobi.getComponent('mainTabs');
    var maintab = mainTabstrip.getTabs().getActiveTabIndex();
    querystring = "?maintab=" + maintab;
    
    // get the service tab also
    if (maintab == SERVICES_TAB_INDEX)
    {
        servicetab = mainTabstrip.getTabs().get(SERVICES_TAB_INDEX).getIframeHtmlNode().contentWindow.document.getElementById('servicesTabs').jsObject.getTabs().getActiveTabIndex();
        querystring += "&servicetab=" + servicetab;
    }
    return querystring;
}

//initialLogin = false if the form was shown because the session expired
var isInitialLogin = true;
function loginLightBox(initialLogin)
{
    isInitialLogin = initialLogin;
    
	Lightview.show({
	  href: 'server/ajaxLogin.ashx?get=form',
	  rel: 'ajax',
	  title: '',
	  options: {
	    //width: 300, 
	    //height: 200,
	    autosize: true,
		ajax: {
		  onComplete: function(){
		    $('loginSubmit').observe('click', submitAjaxLogin);
		  } 
	    }
	  }
	}); 
	/*if (refreshAfter)
	{
        document.observe('lightview:hidden', function(event) {
            refresh();
        });	
	} */  
}

function submitAjaxLogin(event) {
  // block default form submit
  event.stop();
	  
  Lightview.show({
    href: 'server/ajaxLogin.ashx',
    rel: 'ajax',
    options: {
      title: 'results',
	  menubar: false,
	  autosize: true,
	  topclose: false,
      ajax: {
        parameters: Form.serialize('ajaxLoginForm'),
	    onComplete: function(){
	        if ($('loginSuccessful').value == 'true') {
	            if (isInitialLogin) {
	                if(!($('btnAddSubscription'))) {
	                    refresh();
	                }
	            }
	            else {
	                Lightview.hide();
	            }
	        }
	        else {
	            $('loginSubmit').observe('click', submitAjaxLogin); 
	        }
	    }         
      }
    }
  });
  
  //setTimeout("Lightview.hide(); SessionLoop();", 5000);
}

function cancelAjaxLogin(event)
{
    event.stop();
    
    Lightview.hide();
}

//shows the signup lightbox
function ShowSignup()
{
    Lightview.show({
	  href: 'server/signup.ashx?get=form',
	  rel: 'ajax',
	  options: {
	  	topclose: true,
	    autosize: true,
		ajax: {
		  onComplete: function(){
		    // once the request is complete we observe the submit button
			$('signupSubmit').observe('click', submitSignup);
			$('signupCancel').observe('click', cancelSignup);
		  } 
	    }
	  }
	});
}

//submits the signup form, and shows a lightbox with the results
function submitSignup(event) {
  // block default form submit
  event.stop();
	  
  Lightview.show({
    href: 'server/signup.ashx',
    rel: 'ajax',
    options: {
	  topclose: true,
	  autosize: true,
      ajax: {
        parameters: Form.serialize('signupForm'), // the parameters from the form
		  onComplete: function(){
		    // once the request is complete we observe the submit button
		    if ($('signupSuccessful').value != "true")
		    {
			    $('signupSubmit').observe('click', submitSignup);
			    $('signupCancel').observe('click', cancelSignup);
			}
			else {
			    document.observe('lightview:closed', function(event) {
                    refresh();
                });
			}
		  }         
      }
    }
  });
  
  //window.setTimeout("if ($('signupSuccessful').value == \"true\") refresh();", 3000);
}

function cancelSignup(event)
{
    event.stop();
    
    Lightview.hide();
}

//refreshes the current page
function refresh()
{
    //  This version does NOT cause an entry in the browser's
    //  page view history.  Most browsers will always retrieve
    //  the document from the web-server whether it is already
    //  in the browsers page-cache or not.
    //  
    if (returnUrl != "") {
        window.location.replace( sURL + returnUrl );
    }
    else {
        window.location.replace( sURL + StateQueryString() );
    }
}

//shows the addwatch lightview window
function AddWatchlistItem(grid)
{
    if (!LoggedIn)
    {
        loginLightBox(true); 
    }
    else
    {
        Lightview.show({ title: 'Add a new Watch List Item', href: 'addWatch.aspx', rel: 'iframe', options: { width: 450, height:385 }});
        document.observe('lightview:hidden', function(event) {
                refreshWatchlist();
            });
    }
}

// refreshes the watchlist grid
function refreshWatchlist()
{
    var watchlistGrid = nitobi.getComponent('mainTabs').getTabs().get(SERVICES_TAB_INDEX).getIframeHtmlNode().contentWindow.document.getElementById('servicesTabs').jsObject.getTabs().get(WATCHLIST_TAB_INDEX).getIframeHtmlNode().contentWindow.document.getElementById('WatchlistGrid').jsObject;
    watchlistGrid.subscribeOnce("dataready",function () { nitobi.getComponent('SearchGrid').loadingScreen.hide(); });    
    watchlistGrid.loadingScreen.show();             
    watchlistGrid.clearSurfaces();
    watchlistGrid.dataBind();
}

//passes the category filter down to the search tab
function CategorySearch(categoryId)
{
    var mainTs = nitobi.getComponent('mainTabs');
    var servicesTab = mainTs.getTabs().get(SERVICES_TAB_INDEX);

    if (servicesTab.getContentLoaded())
    {
        mainTs.getTabs().setActiveTab(servicesTab);    
        ServicesContentReady(servicesTab, categoryId);
    }
    else
    {
        servicesTab.setSource("Services.aspx?servicetab=1");
        mainTs.getTabs().setActiveTab(servicesTab);    
        waitForContent(categoryId);
    }
}

//waits for the Services Content to be loaded
function waitForContent(categoryId)
{
    var mainTs = nitobi.getComponent('mainTabs');
    var servicesTab = mainTs.getTabs().get(SERVICES_TAB_INDEX);

    if (servicesTab.getContentLoaded())
    {
        ServicesContentReady(servicesTab, categoryId);
    }
    else
    {
        setTimeout("waitForContent(" + categoryId + ")",200);
    }
}

//when the services content is ready, call CategorySearch to filter by category
function ServicesContentReady(servicesTab, categoryId)
{
    servicesTab.getIframeHtmlNode().contentWindow.CategorySearch(categoryId);
}

var valid = false;
function validateSignupForm()
{
    valid = true;
    
    if ( !($('tosCheckbox').checked) )
        valid = false;
    if ($('username').value == "")
        valid = false;
    if ($('password').value == "")
        valid = false;
    if ($('password').value != $('rptPassword').value)
        valid = false;
    if ($('email').value == "")
        valid =false;
    if (valid)
        nitobi.html.Css.swapClass($('signupSubmit'),'signup-submit-null','signup-submit-active');
    else
        nitobi.html.Css.swapClass($('signupSubmit'),'signup-submit-active','signup-submit-null');
}

//check the current status of the Signup Form validation
//valid - a variable constantly updated on the validity of the signup form
function checkSignupForm()
{
    if (valid)
        return true;
    else
        return false;
}

//adds a watchowner to the watch list via ajax
function WatchOwner(name, callback)
{
    var xhr = new nitobi.ajax.HttpRequest();
    xhr.handler = "server/addWatch.ashx?owner=" + name;
    xhr.async = true; // async is true by default
    xhr.responseType = "text"; // by default the appropriate responseType will be used - ie XML if the data is valid XML otherwise "text".
    xhr.onGetComplete.subscribeOnce(callback);

    watchStatusDiv = $("lightviewContent").contentWindow.document.getElementById("buttonWatchOwner");
    watchStatusDiv.style["opacity"] = "0.5";
    watchStatusDiv.innerHTML = "<img src=\"css\grid\nitobi\loading.gif\" />";     
    
    //using a post here caused a "length required" issue on the cisense live server
    xhr.get();  
	
	
	refreshWatchlist();
	
}

//notify the user when a watch item has ben added successfully from the details window
var watchStatusDiv;
function DetailsWatchAdded(eventArgs)
{
    if (eventArgs.response == "success")
    {
        watchStatusDiv.innerHTML = "<div style=\"margin-top:5px;\">watch added</div>";
        setTimeout("watchStatusDiv.innerHTML = ''", 3000);
    }
}    

//shows the services tab.
//tabIndex - the index of the services tab that should be made active
function ShowServices(tabIndex)
{
    var mainTs = nitobi.getComponent('mainTabs');
    var servicesTab = mainTs.getTabs().get(SERVICES_TAB_INDEX);

    if (servicesTab.getContentLoaded())
    {
        mainTs.getTabs().setActiveTab(servicesTab);    
        servicesTab.getIframeHtmlNode().contentWindow.nitobi.getComponent('servicesTabs').getTabs().setActiveTab(tabIndex);
    }
    else
    {
        servicesTab.setSource("Services.aspx?servicetab=1");
        mainTs.getTabs().setActiveTab(servicesTab); 
        waitForServicesTab(tabIndex);
    }    
}

function waitForServicesTab(tabIndex)
{
    var mainTs = nitobi.getComponent('mainTabs');
    var servicesTab = mainTs.getTabs().get(SERVICES_TAB_INDEX);

    if (servicesTab.getContentLoaded())
    {
        servicesTab.getIframeHtmlNode().contentWindow.nitobi.getComponent('servicesTabs').getTabs().setActiveTab(tabIndex);
    }
    else
    {
        setTimeout("waitForServicesTab(" + tabIndex + ")",200);
    }
}

//this hides and shows flash videos, as they appear on top of the lightview overlay.
//only set to check the certain tabs known to have flash content
function SetFlashVisibilityCss(visibility)
{
    //damn nested tabstrips
    var tabs = nitobi.getComponent('mainTabs').getTabs();
    var activeNode = tabs.getActiveTab().getIframeHtmlNode();
    var objects = activeNode.contentWindow.document.getElementsByTagName('object');
    var i=0;
    
    if (tabs.getActiveTabIndex() == HOME_TAB_INDEX)
    {
        for (i=0; i<objects.length; i++)
        {
            objects[i].style["visibility"] = visibility;
        }
    }
    else if (tabs.getActiveTabIndex() == SERVICES_TAB_INDEX && activeNode.contentWindow.nitobi.getComponent('servicesTabs').getTabs().getActiveTabIndex() == SAMPLES_TAB_INDEX)
    {
        objects = activeNode.contentWindow.nitobi.getComponent('servicesTabs').getTabs().getActiveTab().getIframeHtmlNode().contentWindow.document.getElementsByTagName('object');
        i=0;
        for (i=0; i<objects.length; i++)
        {
            objects[i].style["visibility"] = visibility;
        }    
    }
    

}

//when the Services tab is activated, we may have to resize the tabstrip(s) if the Overview tab is active
function ServicesActivated(tab)
{
    var tabWindow = tab.getIframeHtmlNode().contentWindow;
    
    if(tab.getContentLoaded() && tabWindow.nitobi.getComponent('servicesTabs').getTabs().getActiveTabIndex() == SAMPLES_TAB_INDEX)
    {
        tabWindow.growTabs(); 
    }
    
}

function AddSubscription()
{
    Lightview.show({ href: 'Details.aspx?addservice=true', rel: 'iframe', options: { width: 450, height:320 }});
}

function ShowFaq()
{
    Lightview.show({ href: 'faq.htm', title:'Frequently Asked Questions', rel: 'iframe', options: { width: 600, height:500 }});
}

function ShowOverviewSection(id) {
    ShowServices(0);
    //getting the position of these elements, which are inside two nested iframes, proved very difficult,
    //so i had to hardcode these scrollto calls
    if (!nitobi.getComponent('mainTabs').getTabs().getActiveTab().getContentLoaded())
    {
        setTimeout("ShowOverviewSection('" + id + "')", 100);
        return;
    }
    switch(id)
    {
        case 'reports':
            ScrollWhenLoaded(1300);
            break;    
        case 'watchlist':
            ScrollWhenLoaded(920);
            break;
        default:
            ScrollWhenLoaded(155);
    }

}

function ScrollWhenLoaded(value) {
    if (nitobi.getComponent('mainTabs').getTabs().getActiveTab().getIframeHtmlNode().contentWindow.document.getElementById('servicesTabs').jsObject.getTabs().get(0).getContentLoaded())
        window.scrollTo(0,value);
    else
        setTimeout("ScrollWhenLoaded(" + value + ")",100);
}