﻿function showClaimWindow(show, siteName, profileID)
{
    var objProfileID = $('claimProfileID');
    $(txtUserName).value = '';
    $(txtPassword).value = '';
    objProfileID.value = profileID;
    
    setSiteName(siteName);
    isBusy(false);
    showClaimMessage('');
    disablePageContents(show);
    $('divClaim').style.display = show ? 'block' : 'none';
}

function setSiteName(siteName)
{
    $('claimSiteName').innerHTML = siteName;
}

function isBusy(busy)
{
    $('divBusy').style.visibility = busy ? 'visible' : 'hidden';
    disableSubmitButton(busy);
}

function showClaimMessage(message)
{
    var obj = $('divClaimMessage');
    obj.style.display = (message.length == 0) ? 'none' : 'block';
    obj.innerHTML = message;    
}

function claimProfile()
{
    var validationResult = Page_ClientValidate('ClaimProfile');
    
    if (validationResult)
    {
        var userName = $(txtUserName).value;
        var password = $(txtPassword).value;
        var profileID = $('claimProfileID').value;
    
        sendClaimRequest(profileID, userName, password);
    }
}

var parseClaimProfileAnswer;

function disableSubmitButton(disable)
{
    var submit = $('claimProfileSubmit');
    if (disable)
    {        
        var href = submit.getAttribute("href");
        
        if (href != null && href != '')
        {
            submit.removeAttribute('href');
            submit.setAttribute('href_bak', href);
        }
    }
    else
    {
        var href = submit.getAttribute("href_bak");
        
        if (href != null && href != '')
        {
            submit.removeAttribute('href_bak');
            submit.setAttribute('href', href);
        }
    }
    
}

function sendClaimRequest(profileID, userName, password)
{
    isBusy(true);
    
    var url = locationClaimProfileXML;
    url = url.replace('{pid}', profileID);
    url = url.replace('{u}', userName);
    url = url.replace('{p}', password);
    url = url.replace('{url}', pageUrl);    
    
    getXMLdoc(url, parseClaimProfileAnswer);
}

parseClaimProfileAnswer = function (xhr)
{
    var xml = xhr.responseText;
    var xmlAnswer;
    if (window.ActiveXObject)
    {
        xmlAnswer = new ActiveXObject("msxml.DOMDocument");
        xmlAnswer.loadXML(xml);
    } else if (document.implementation && document.implementation.createDocument)
    {
        parser = new DOMParser();
        xmlAnswer = parser.parseFromString(xml, "text/xml");
    }
    
	var answer = xmlAnswer.selectSingleNode("/result/answer");
	var success = answer.attributes[0].value;
	var message = answer.attributes[1].value;
	var loginUrl = answer.attributes[2].value;
	
	if (success == 'true')
	{
	    showClaimWindow(false, '', 0);
	}
	else
	{
	    if (loginUrl != '')
	    {
	        location.href = loginUrl;
	    }
	    else
	    {
	        showClaimMessage(message);
	    }
	}
	
	isBusy(false);
}