$(document).ready(function() {
    $('.productList').autocomplete(
        WebTicket.getProductServiceUrl(), {
            minChars:3,
            mustMatch: true,
            matchContains:"word",
            max:1500
        }
    ).result(productSelected);
    
	$('.productList').blur(function() {
		var kbProductId = $('#kbProductId').val();
        browseProductSupport(kbProductId);
    });
	
	$('.productList').bt({
        trigger:'none',
        contentSelector:"$('#suggestedSolutions').html()"
    });
	
    $('.issueSummary').blur(function() {
        searchNeptune($(this).val());
    });
	
	$('.issueSummary').bt({
	    trigger:'none',
	    contentSelector:"$('#searchResults').html()"
	});
	
	$('.email').blur(function() {
		var email = $(this).val();
		if(email.length == 0) {
			hidePasswordPanel();
			return;
		}
		checkIfEmailExists( $(this).val() );		
	});
	
	
	if(typeof(accounts) != 'undefined') {
		if(accounts.length == 1) {
			$("#ContactInformation_AccountNumber").val(accounts[0]);
		}
		
		$("#ContactInformation_AccountNumber").autocomplete(accounts, {
			minChars: 1,
			autoFill: true,
			mustMatch: false,
			matchContains: false,
			scrollHeight:50
		});
	}
	
})

function productSelected(e, data) {
    $("#productName").val(data[0]);
    $("#productId").val(data[1]);
    $("#supportGroupId").val(data[2]);
    $("#functionalSupportGroupId").val(data[3]);
    $("#kbProductId").val(data[4]);
    $("#kbTopicPath").val(data[5]);
}

function checkIfEmailExists(email) {
    if(email != '') {
        $.ajax({
            type:"POST",
            url: WebTicket.getUsersServiceUrl(),
            data:"id=" + email,
            dataType:"json",
            async:true,
            success:function(data) {
                if(data != undefined) {
                    var d = eval(data);
                    if(typeof(d.error) != 'undefined') {
                        alert("Failed to verify existing user");
                    }
					if(d.exists == 'true') {
						hidePasswordPanel();
						$('#ContactInformation_Phone').focus();
                    } else {
						showPasswordPanel();
						$('#ContactInformation_Password').focus();
					}
                }
            },
            error:function(XMLHttpRequest, status, error) {
                alert("Failed to verify existing user, 2");
            }
        });
    }
}

function hidePasswordPanel() {
    $(".passwordSecurity").hide();
    $(".passwordSecurity input[type='text'").attr('enabled','false');
    
    var ContactInformation_rfvPassword = document.all ? document.all["ContactInformation_rfvPassword"] : document.getElementById("ContactInformation_rfvPassword");
    ValidatorEnable(ContactInformation_rfvPassword,false);
    
    var ContactInformation_cfvPassword = document.all ? document.all["ContactInformation_cfvPassword"] : document.getElementById("ContactInformation_cfvPassword");
    ValidatorEnable(ContactInformation_cfvPassword, false);
    
    var ContactInformation_rfvPasswordConfirm = document.all ? document.all["ContactInformation_rfvPasswordConfirm"] : document.getElementById("ContactInformation_rfvPasswordConfirm");
    ValidatorEnable(ContactInformation_rfvPasswordConfirm, false);
    
    var ContactInformation_cfvPasswordConfirm = document.all ? document.all["ContactInformation_cfvPasswordConfirm"] : document.getElementById("ContactInformation_cfvPasswordConfirm");
    ValidatorEnable(ContactInformation_cfvPasswordConfirm, false);
}

function showPasswordPanel() {
    $(".passwordSecurity").fadeIn('slow');
    $(".passwordSecurity input[type='text'").attr('enabled','true');

    var ContactInformation_rfvPassword = document.all ? document.all["ContactInformation_rfvPassword"] : document.getElementById("ContactInformation_rfvPassword");
    ValidatorEnable(ContactInformation_rfvPassword, true);

    var ContactInformation_cfvPassword = document.all ? document.all["ContactInformation_cfvPassword"] : document.getElementById("ContactInformation_cfvPassword");
    ValidatorEnable(ContactInformation_cfvPassword, true);
    
    
    var ContactInformation_rfvPasswordConfirm = document.all ? document.all["ContactInformation_rfvPasswordConfirm"] : document.getElementById("ContactInformation_rfvPasswordConfirm");
    ValidatorEnable(ContactInformation_rfvPasswordConfirm, true);
    
    var ContactInformation_cfvPasswordConfirm = document.all ? document.all["ContactInformation_cfvPasswordConfirm"] : document.getElementById("ContactInformation_cfvPasswordConfirm");
    ValidatorEnable(ContactInformation_cfvPasswordConfirm, true);
}

function validatePasswordLength(source, arguments) {
    var len = arguments.Value.length;
    arguments.IsValid = ((len >= 6) && (len <= 32));
}

function validateSummaryLength(source, arguments) {
    arguments.IsValid = (arguments.Value.length >= 5);
}
        
function validaetDescrLength(source, arguments) {
	arguments.IsValid = (arguments.Value.length >= 10);
}

//************************************************
//* these functions handle browse/search requests
function browseProductSupport(productId) {

	if((productId == '') || (typeof(productId) == 'undefined')) {    
        return false;
    }
    $.ajax({
        type: "POST",
        url: WebTicket.getBrowseServiceUrl(),
        data: "prodid=" + productId,
        dataType: "json",
        async: true,
        success: showProductSupportBrowseResults,
        error: function(XMLHttpRequest, status, error) {
            alert('Sorry, unexpected system error');
        }
    });
}

function browseNeptune(path) {
    if((path == '') || (typeof(path) == 'undefined')) {
        return false;
    }
	$.ajax({
		type:"POST",
		url: "/neptune/browse.do",
		data: "path=" + path + "&format=json",
		dataType: "json",
		async: true,
		success: showNeptuneBrowseResults,
		error: function(XMLHttpRequest, status, error) {
			if(typeof(status) != 'undefined') {
				if((status == 'parsererror') || (status == 'error')) {
					var result = {"resultSet": {
					        "topicPath":path,
					        "documentCount":0,
					        "result":[]
					    }
					};
					
					showNeptuneBrowseResults(result,status);
				}
			}
		}
	});
}

function searchNeptune(searchTerm) {
	var searchPath = $('#kbTopicPath').val();
	if(typeof(searchPath) == 'undefined') searchPath = '';
	if(searchTerm != "") {
		$.ajax({
			type: "POST",
			url: WebTicket.getSearchServiceUrl(),
			data: "q=" + searchTerm + "&p=" + searchPath + "&format=xml&cluster=DefaultCluster",
			dataType: "xml",
			async: true,
			success: showSearchNeptuneResults,
			error: function(XMLHttpRequest, status, error ) {
				alert('Sorry, unexpected system error');
			}
		});
	}
}
//************************************************

//******************************************************
//* these functions display browse results
function showProductSupportBrowseResults(data, status) {
	$("#suggestedSolutions .helpContent").html("");
	$("#suggestedSolutions .status").html('');
	$(".productList").btOff();

	var d = eval(data);	
	
	if((typeof(d.solutions) == 'undefined') || (d.solutions.length == 0)) {
		browseNeptune($("#kbTopicPath").val());	
	} else {
		$.each(d.solutions, function(i,item) {
			if(i < 10) {
				var url = item.url;
				var pattern = new RegExp('^http|\/');
				if(!pattern.test(url)) {
					url = '/productsupport/' + url;
				}
				var a = $("<a>").attr("href", url).attr("target","_blank").text(item.title);
				$("#suggestedSolutions .helpContent").append( $("<li>").html(a) );
			} else {
				$("#suggestedSolutions .helpContent").append('<a href="/productsupport" target="_blank">more...</a>');
				return false;
			}
		});
		$(".productList").btOn();
	}
}

function showNeptuneBrowseResults(data, status) {
	$("#suggestedSolutions .helpContent").html("");
	$("#suggestedSolutions .status").html('');
	$(".productList").btOff();
	var d = eval(data);
		
	if(data != undefined) {
	    if(d.resultSet.documentCount > 0) {
	        $(d.resultSet.result).each(function(){
	            var a = $("<a>").attr("href", WebTicket.getSolutionUrl(this.solutionId)).attr("target","_blank").text(this.title);
	            $("#suggestedSolutions .helpContent").append( $("<li>").html(a) );
	        });
	    } else {
	        $("#suggestedSolutions .status").html('').html("<p>No supporting articles found</p>");
	    }
	    $(".productList").btOn();    
	}
}

function showSearchNeptuneResults(xml, status) {
    $("#searchResults .helpContent").html("");
    $(".issueSummary").btOff();
    if(status == "success") {
        var responseCount = $('answer',xml).attr('responseCount');
        if((+responseCount) > 0) {
            $('response',xml).each(function(i) {
                if(i < 10) {
                    var responseTitle = $(this).find("text").text();
                    var solutionId = $(this).find("properties").find("meta[name='$solution_id']").attr('content');
                    var a = $("<a>").attr("href", WebTicket.getSolutionUrl(solutionId)).attr("target","_blank").text(responseTitle);
                    $("#searchResults .helpContent").append( $("<li>").html(a) );
                } else {
				    $("#searchResults .helpContent").append('<a href="' + WebTicket.getAnswersUrl() + '" target="_blank">more...</a>');
				    return false;
			    }
            });
        } else {
            $("#searchResults .status").html('').html("<p>No search results found</p>");
        }
        $(".issueSummary").btOn();
    } else {
        $("#searchResults").html('').html("<p>There was a problem with the search request</p>");
    }
}
//******************************************************
