/**
 * Start page functionality
 */

/**
 * Initialize LexLiveStartPage obj when jQuery raises 'document load' 
 */
$(function()
{
	LexLiveStartPage.Initialize();
});


/**
* LexLiveStartPage static object declaration.
* Contains logic for start page
*/
LexLiveStartPage = function() { };

// vars
LexLiveStartPage._isEnabled = true;
LexLiveStartPage._isInitialized = false;
//LexLiveStartPage._loginFrameWidth = 0;
//LexLiveStartPage._loginFrameHeight = 0;
//LexLiveStartPage._loginFrameInitialized = false;

// constants
LexLiveStartPage.DIALOGPAGE_REL_URL = '/Pages/ServicePages/DialogFramePage.aspx';
LexLiveStartPage.LOGINCONTROLPAGE_REL_URL = '/Pages/ServicePages/LoginFramePage.aspx';
LexLiveStartPage.UCPAGE_REL_URL = '/Pages/ServicePages/UCFramePage.aspx';
LexLiveStartPage.INDIRECT_LOGIN_PAGE_REL_URL = '/Pages/ServicePages/IndirectLogin.aspx';
LexLiveStartPage.REGISTRATION_DIALOG = 'RegistrationDialog';
LexLiveStartPage.PRODUCT_TOUR_DIALOG = 'ProductTourDialog';
LexLiveStartPage.SECURITY_DIALOG = 'LPSecurityDialog';
LexLiveStartPage.PAGENAME = 'StartPageAppURL';


// read-only fields
LexLiveStartPage.DIALOGPAGE_URL = ''; // initialized later
LexLiveStartPage.LOGINCONTROLPAGE_URL = ''; // initialized later
LexLiveStartPage.BLOGLISTPAGE_URL = ''; // initialized later
LexLiveStartPage.INDIRECT_LOGIN_PAGE_URL = ''; // initialized later


/**
*  Initialize
*/
LexLiveStartPage.Initialize = function()
{
    // set urls
    LexLiveStartPage.DIALOGPAGE_URL = LexLiveStartPageSettings.MAIN_SITE_URL + LexLiveStartPage.DIALOGPAGE_REL_URL;
    LexLiveStartPage.LOGINCONTROLPAGE_URL = LexLiveStartPageSettings.MAIN_SITE_URL + LexLiveStartPage.LOGINCONTROLPAGE_REL_URL;
    LexLiveStartPage.INDIRECT_LOGIN_PAGE_URL = LexLiveStartPageSettings.MAIN_SITE_URL + LexLiveStartPage.INDIRECT_LOGIN_PAGE_REL_URL;
    LexLiveStartPage.BLOGLISTPAGE_URL = LexLiveStartPageSettings.MAIN_SITE_URL + LexLiveStartPage.UCPAGE_REL_URL;

    // bind event handlers to elements, init frames
    $(window).bind("resize", LexLiveStartPage.OnWindowResize);
    $("body").click(function(event) { LexLiveStartPage.OnCommonClick(event); });
    $("#loginIframe").attr("src", LexLiveStartPage.LOGINCONTROLPAGE_URL + "?client=" + LexLiveStartPage.PAGENAME).load(LexLiveStartPage.LoginControlFrameLoaded);
    //? $('#dialogHolder').bind("resize", LexLiveStartPage.OnWindowResize);

    $("#blogListFrame").attr("src", LexLiveStartPage.BLOGLISTPAGE_URL+"?uc=vbulletinTopBlogList");

    LexLiveStartPage._isInitialized = true;

    LexLiveStartPage.SaveAffiliateInfoInCookies();

    // embed flash into the start page
    /*
    if (FlashController.isFlashEnabled())
    {
        FlashController.embedFlash();
    }
    else
    {
        LexLiveStartPage.ShowFlashNotAccessibleDialog();
    }
    */
    
    // IE 6 (or less) is not supported
    if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 7)
    {
        LexLiveStartPage.ShowBrowserNotSupportedDialog();
    }

    // test code
    //debug LexLiveStartPage.ShowErrorDialog('Some error text');
};


/* Global handlers ---------------------------------------------------------------------*/

/**
* Handler for body.click
*/
LexLiveStartPage.OnCommonClick = function(event)
{
	var clickedLink = $(event.target).closest("a");
	if (clickedLink.length > 0)
	{
		LexLiveStartPage.ProcessCommonLinkClick(clickedLink.get(0));
	}
};

/**
* Handler for window.resize
*/
LexLiveStartPage.OnWindowResize = function()
{
	//x LexLiveStartPage.RecalculateDialogFrameSize();
};


/* Common functionality  ---------------------------------------------------------------------*/

/**
* Process common click on links
*/
LexLiveStartPage.ProcessCommonLinkClick = function(target)
{
    var href = $(target).attr("href");
    var hashText, hashCommand, hashCommandArg;

    // extract hash command
    if (href.indexOf('#') > -1)
    {
        hashText = href.substr(href.indexOf('#') + 1);

        if (hashText)
        {
            if (hashText.indexOf('-') > -1)
            {
                hashCommand = hashText.substr(0, hashText.indexOf('-'));
                hashCommandArg = hashText.substr(hashText.indexOf('-') + 1);
            }
            else
            {
                hashCommand = hashText;
            }
        }
    }

    // process hash command
    if (hashCommand)
    {
        switch (hashCommand)
        {
            case 'dialog':
                LexLiveStartPage.OpenDialog(hashCommandArg);
                break;

            /*
            case 'flash':
                switch (hashCommandArg)
                {
                    case 'IntroVideo':
                        FlashController.StartIntroVideo();
                        break;
                }
                break;
            */
            
            case 'errorDialog':
                switch (hashCommandArg)
                {
                    case 'close':
                        LexLiveStartPage.CloseErrorDialog();
                        break;
                }
                break;

            case 'benefitsDialog':
                switch (hashCommandArg)
                {
                    case 'open':
                        LexLiveStartPage.ShowBenefitsDialog();
                        break;
                    case 'close':
                        LexLiveStartPage.CloseBenefitsDialog();
                        break;
                }
                break;

            case 'productOverviewDialog':
                switch (hashCommandArg)
                {
                    case 'open':
                        LexLiveStartPage.ShowProductOverviewDialog();
                        break;
                    case 'close':
                        LexLiveStartPage.CloseProductOverviewDialog();
                        break;
                }
                break;

            case 'securityDialog':
                switch (hashCommandArg)
                {
                    case 'open':
                        LexLiveStartPage.ShowSecurityDialog();
                        break;
                    case 'close':
                        LexLiveStartPage.CloseSecurityDialog();
                        break;
                    case 'print':
                        LexLiveStartPage.PrintSecurityDialog();
                        break;
                }
                break;

            case 'browserNotSupportedDialog':
                if (hashCommandArg == 'close')
                {
                    LexLiveStartPage.CloseBrowserNotSupportedDialog();
                }
                break;
        }
    }
};


/* Dialogs in frame functionality  ---------------------------------------------------------------------*/

/**
* Open a dialog using iframe
*/
LexLiveStartPage.OpenDialog = function(dialogName)
{
	$("#dialogHolder")
		.css("display", "block");
	$("#dialogFrame")
		.css("display", "block")
		.css("visibility", "hidden");

	// prepare dialog page parameters
	var dialogPageParameters = "?dialogname=" + dialogName + '&client=' + LexLiveStartPage.PAGENAME;

	if (dialogName == LexLiveStartPage.REGISTRATION_DIALOG)
	{
		// add affiliate data from cookies
		if ($.cookie('AFFILINET'))
		{
			dialogPageParameters += '&ref=' + $.cookie('AFFILINET');
		}
		if ($.cookie('ZANOX'))
		{
			dialogPageParameters += '&zanpid=' + $.cookie('ZANOX');
		}
		if ($.cookie('TRADEDOUBLER'))
		{
			dialogPageParameters += '&tduid=' + $.cookie('TRADEDOUBLER');
		}
		// add google ad word
		if ($.cookie('GOOGLE_ADWORD'))
		{
			dialogPageParameters += '&adword=' + $.cookie('GOOGLE_ADWORD');
		}
	}

	$("#dialogFrame").attr("src", LexLiveStartPage.DIALOGPAGE_URL + dialogPageParameters).load(LexLiveStartPage.DialogFrameLoaded);
};

/**
* Process close dialog command
*/
LexLiveStartPage.CloseDialog = function()
{
	LexLiveStartPage.HideDialogFrame();
};

/**
* Hide dialog frame
*/
LexLiveStartPage.HideDialogFrame = function()
{
	$("#dialogHolder").css("display", "none");
	$("#dialogFrame").css("display", "none");
};

/**
* Process dialog iframe loaded
*/
LexLiveStartPage.DialogFrameLoaded = function()
{
	$("#dialogFrame").css("visibility", "visible");
};

/**
* Recalculate dialog frame size
*/
LexLiveStartPage.RecalculateDialogFrameSize = function()
{
	$("#dialogContent").attr("width", $(window).width()).attr("height", $(window).height());
	$("#dialogFrame").attr("width", $(window).width()).attr("height", $(window).height());
};


/* Login in frame functionality  ---------------------------------------------------------------------*/

/**
* Process user login
*/
LexLiveStartPage.OnLogin = function(cookie)
{
	// redirect to main site
	window.location = LexLiveStartPage.INDIRECT_LOGIN_PAGE_URL + "?auth=" + cookie;
};

/**
* Process login iframe loaded
*/
LexLiveStartPage.LoginControlFrameLoaded = function()
{
	$("#loginHolder").css("display", "block");
};

/**
* Resize login frame
*/
LexLiveStartPage.ResizeLoginFrame = function(resizeMode)
{
	switch (resizeMode)
	{
		case 'full':
			$("#loginHolder").css("width", $(window).width());
			$("#loginHolder").css("height", $(window).height());
			break;

		case 'normal':
			$("#loginHolder").css("width", LexLiveStartPage._loginFrameWidth);
			$("#loginHolder").css("height", LexLiveStartPage._loginFrameHeight);
			break;
	}

	$("#loginHolder").css("display", "block");
};

/**
* Hide login frame
*/
LexLiveStartPage.HideLoginFrame = function()
{
	$("#loginHolder").css("display", "none");
	$("#loginIframe").css("display", "none");
};


/* Errors processing/Error dialog  ---------------------------------------------------------------------*/

/**
* Process error from command frame
*/
LexLiveStartPage.OnCommandFrameError = function(errMsg)
{
	// make frames invisible
	LexLiveStartPage.HideDialogFrame();
	LexLiveStartPage.HideLoginFrame();

	// show err
	errMsg = decodeURIComponent(errMsg);
	LexLiveStartPage.ShowErrorDialog(errMsg);
};

/**
* Show benefits dialog
*/
LexLiveStartPage.ShowBenefitsDialog = function()
{
    $(window).bind("resize", { dialogID: "#benefitsDialog", dialogWidth: 780 }, LexLiveStartPage.RepositionClientDialog);

    LexLiveStartPage.RepositionClientDialog({ data: { dialogID: "#benefitsDialog", dialogWidth: 780} });
};


/**
* Hide benefits dialog
*/
LexLiveStartPage.CloseBenefitsDialog = function()
{
    $(window).unbind("resize", LexLiveStartPage.RepositionClientDialog);

    $("#modalBackground").css("display", "none");
    $("#benefitsDialog").css("display", "none");
};


/**
* Show security dialog
*/
LexLiveStartPage.ShowSecurityDialog = function()
{
    $(window).bind("resize", { dialogID: "#securityDialog", dialogWidth: 680, dialogHeight: 545 }, LexLiveStartPage.RepositionClientDialog);

    LexLiveStartPage.RepositionClientDialog({ data: { dialogID: "#securityDialog", dialogWidth: 680, dialogHeight: 545} });
};


/**
* Hide security dialog
*/
LexLiveStartPage.CloseSecurityDialog = function()
{
    $(window).unbind("resize", LexLiveStartPage.RepositionClientDialog);

    $("#modalBackground").css("display", "none");
    $("#securityDialog").css("display", "none");
};

LexLiveStartPage.PrintSecurityDialog = function()
{
    $("#securityDialogIframe").get(0).contentWindow.focus();
    $("#securityDialogIframe").get(0).contentWindow.print();
};

/**
* Show product overview dialog
*/
LexLiveStartPage.ShowProductOverviewDialog = function()
{
    $(window).bind("resize", { dialogID: "#productOverviewDialog", dialogWidth: 680, dialogHeight: 545 }, LexLiveStartPage.RepositionClientDialog);

    LexLiveStartPage.RepositionClientDialog({ data: { dialogID: "#productOverviewDialog", dialogWidth: 680, dialogHeight: 545} });
};


/**
* Hide product overview dialog
*/
LexLiveStartPage.CloseProductOverviewDialog = function()
{
    $(window).unbind("resize", LexLiveStartPage.RepositionClientDialog);

    $("#modalBackground").css("display", "none");
    $("#productOverviewDialog").css("display", "none");
};

/**
* Show error dialog
*/
LexLiveStartPage.ShowErrorDialog = function(errMsg)
{
    $(window).bind("resize", { dialogID: "#errorDialog", dialogWidth: 420 }, LexLiveStartPage.RepositionClientDialog);

    $("#errorDialogText").text(errMsg);

    LexLiveStartPage.RepositionClientDialog({ data: { dialogID: "#errorDialog", dialogWidth: 420} });
};

/**
* Hide error dialog
*/
LexLiveStartPage.CloseErrorDialog = function()
{
    $(window).unbind("resize", LexLiveStartPage.RepositionClientDialog);

    $("#modalBackground").css("display", "none");
    $("#errorDialog").css("display", "none");
};

/**
* Show "flash not accessible" dialog
*/
LexLiveStartPage.ShowFlashNotAccessibleDialog = function()
{
    $(window).bind("resize", { dialogID: "#flashNotAccessibleDialog", dialogWidth: 420 }, LexLiveStartPage.RepositionClientDialog);

    LexLiveStartPage.RepositionClientDialog({ data: { dialogID: "#flashNotAccessibleDialog", dialogWidth: 420} });
};

/**
* Show "browser not supported" dialog
*/
LexLiveStartPage.ShowBrowserNotSupportedDialog = function()
{
    $(window).bind("resize", { dialogID: "#browserNotSupportedDialog", dialogWidth: 420 }, LexLiveStartPage.RepositionClientDialog);

    LexLiveStartPage.RepositionClientDialog({ data: { dialogID: "#browserNotSupportedDialog", dialogWidth: 420} });
};

/**
* Close "browser not supported" dialog
*/
LexLiveStartPage.CloseBrowserNotSupportedDialog = function()
{
    $(window).unbind("resize", LexLiveStartPage.RepositionClientDialog);

    $("#modalBackground").css("display", "none");
    $("#browserNotSupportedDialog").css("display", "none");
};

/**
* Reposition client dialog
*/
LexLiveStartPage.RepositionClientDialog = function(e)
{
    $("#modalBackground").css("display", "none");
    $(e.data.dialogID).css("display", "none");

    var xpos = ($(window).width() - e.data.dialogWidth) / 2;
    xpos = (xpos > 0) ? xpos : 0;

    $("#modalBackground")
        .css("width", $(window).width())
        .css("height", $(window).height())
        .css("display", "block");

    $(e.data.dialogID)
        .css("display", "block")
        .css("left", xpos);

    if (e.data.dialogHeight)
    {
        var ypos = ($(window).height() - e.data.dialogHeight) / 2;
        ypos = (ypos > 0) ? ypos : 0;

        $(e.data.dialogID).css("top", ypos);
    }
};

/* Affiliate cookies ---------------------------------------------------------------------*/

/**
* Save affiliate info in cookies
*
* if the query string contains key "ref" a cookie named AFFILINET shall be stored on the client side
*
* if the query string contains a key "zanpid" a cookie with the name ZANOX shall be stored on the client side
*
* if the query string contains a key "tduid" a cookie with the name TRADEDOUBLER shall be stored on the client side.
*
*/
LexLiveStartPage.SaveAffiliateInfoInCookies = function()
{
	var COOKIE_EXPIRE_DAYS = 30;
	var parsedUrl = LexLiveStartPageUtility.ParseUrl(document.URL);

	var currentCookies =
		'AFFILINET: ' + $.cookie('AFFILINET') + "\n" +
		'ZANOX: ' + $.cookie('ZANOX') + "\n" +
		'TRADEDOUBLER: ' + $.cookie('TRADEDOUBLER');

	if (parsedUrl.QueryString)
	{
		// read 'ref', 'zanpid', newsletter parameters from url
		if (parsedUrl.QueryString.ref)
		{
			var refValue = parsedUrl.QueryString.ref;
			LexLiveStartPage.SetCookieValue('AFFILINET', refValue, COOKIE_EXPIRE_DAYS);
		}
		if (parsedUrl.QueryString.zanpid)
		{
			var zanpidValue = parsedUrl.QueryString.zanpid;
			LexLiveStartPage.SetCookieValue('ZANOX', zanpidValue, COOKIE_EXPIRE_DAYS);
		}
		if (parsedUrl.QueryString.tduid)
		{
			var tduidValue = parsedUrl.QueryString.tduid;
			LexLiveStartPage.SetCookieValue('TRADEDOUBLER', tduidValue, COOKIE_EXPIRE_DAYS);
		}
		// read google adword from url
		if (parsedUrl.QueryString.adword)
		{
			var adwordValue = parsedUrl.QueryString.adword;
			LexLiveStartPage.SetCookieValue('GOOGLE_ADWORD', adwordValue, COOKIE_EXPIRE_DAYS);
		}
	}
};

/**
* Set cookie value
*
*/
LexLiveStartPage.SetCookieValue = function(cookieName, cookieValue, expireDays)
{
	var options = { path: '/', expires: expireDays };

	$.cookie(cookieName, cookieValue, options);

	/* examples
	
	var COOKIE_NAME = 'test_cookie';
	var ADDITIONAL_COOKIE_NAME = 'additional';
	var options = { path: '/', expires: 10 };
                
	// set cookie by number of days
	$.cookie(COOKIE_NAME, 'test', options);
                
	// set cookie by date
	var date = new Date();
	date.setTime(date.getTime() + (3 * 24 * 60 * 60 * 1000));
	$.cookie(COOKIE_NAME, 'test', { path: '/', expires: date });
	
	// get cookie
	alert($.cookie(COOKIE_NAME));
	
	// delete cookie
	$.cookie(COOKIE_NAME, null, options);
	
	// set a second cookie
	$.cookie(ADDITIONAL_COOKIE_NAME, 'aou?;foo=bar', { expires: 10 });
	
	// get second cookie
	alert($.cookie(ADDITIONAL_COOKIE_NAME));
	
	// delete second cookie
	$.cookie(ADDITIONAL_COOKIE_NAME, null);
	*/
};
