var DebugOn = false ;
var LastMethodCalled;
var LastMethodVars; //set by the originating method
//Webmethod call handlers
function CallWebMethodV2(f) {
    try {
        MyUnTip();
        LastMethodCalled = f + "///" + LastMethodVars;
        f();
    }
    catch (ex) {
        if (ex.name == 'TypeError' || ex.name == 'ReferenceError') {
            try {
                var ErrorInfo = "Redirect to logon: " + ex.name + "/" + ex.message + " / " + ex.stack;
                LogGenericError(ErrorInfo, f);
            }
            catch (ex2) {
            //do nothing if logging doesn't work
            }
            
            NotifyAndRedirectToLogin();
        }
        else {
            try {
                var ErrorInfo = "Unexpected error: " + ex.name + "/" + ex.message + " / " + ex.stack;
                LogGenericError(ErrorInfo, f);
            }
            catch (ex2) {
                //do nothing if logging doesn't work
            }
            alert('An unexpected error occured.');
        }
    }
}
function CallMethodSuccess(Result, f) {
    if (typeof(f) != 'undefined')
        f(Result);
    if (Result.GenericErrorOccurred == true) {
        alert(Result.GenericErrorMessage);
    }
}
function CallMethodFailure(ex, f) {
    GenericError(ex, f);
    if (typeof(f) != 'undefined')
        f(ex);
}
function GenericError(ex, f) {
    if (ex.get_exceptionType() == 'System.ApplicationException') {
        alert('Error:\r\n\r\n' + ex.get_message());
    }
    //i'm not sure why, but testing a call in ie8 after the user is no longer logged in caused a 12030 to be returned.
    else if (ex.get_statusCode() == '401' || ex.get_statusCode() == '12030') {
        NotifyAndRedirectToLogin();
    }
    else {
        var ErrorInfo = ex.get_statusCode() + "/" + ex.get_exceptionType() + " / " + ex.get_message();
        LogGenericError(ErrorInfo, f);
        alert("An unexpected error occurred. /" + ErrorInfo);
    }
}

function LogArgs(args) {
    for (var i = 0; i < args.length; i++) {
        LastMethodVars += " / Arg" + i + ":" + args[i];
    }
}

function LogGenericError(Msg, f) {
    var FunctionText = "";
    if (typeof(f) != 'undefined') {
        FunctionText = f.toString();
    }
    FunctionText += " / Last Method: " + LastMethodCalled;
    var GenericWebServiceInput =
        {
            "NameValuePairs": {
                "Function": FunctionText,
                "ErrorMsg": Msg,
                "PageURL": location.href
            }
        };

        MplaceV2.LogError(GenericWebServiceInput);
}

function NotifyAndRedirectToLogin() {
    alert('You are no longer logged in.  You will now be redirected to the logon page.');
    location.href = "/content/Logon.aspx";
}

function HTTPRequestGlobalReturnFunction(ReturnReq) {
    if (ReturnTextValueAtPath(ReturnReq.responseXML, "/xml/InfoType") == "notloggedin") {
        window.alert("You have been logged off due to inactivity.");
        location.href = "/content/Logon.aspx";
    }
    else if (ReturnTextValueAtPath(ReturnReq.responseXML, "/xml/InfoType") == "shouldusessl") {
        window.alert("You must access the Marketplace with security.  We will now redirect you to the secured version of the site.");
        location.href = "/content/home.aspx";
    }
}

function InitElementsV2(Ele) {
    $("[name=boxshowhidetoggle][boxshowhidewired!='true']", Ele)
    .attr("boxshowhidewired", "true")
    .click(function() {
        $(this).parent().next().toggle(400);
        $(this).parent().hide();
        return false;
    });

    $("[HelpTextDialogText][HelpTextDialogTextWired!='true']", Ele)
    .attr("HelpTextDialogTextWired", "true")
    .mouseover(
    function(e) {
    MyTip($(this).attr("HelpTextDialogText"));
    }
    ).mouseout(
    function(e) {
        MyUnTip();
    }
    ).addClass("HelpTextDialogLink");
    //$("[FunctionOnEnter]").bind("keydown", function(e){HandleFireOnEnterKeyDown(e)});
    //$("[IDOfControlToFireOnclickOnEnter]").bind("keydown", function(e){HandleFireOnEnterKeyDown(e)});
    
    $("[textmatchtype='StockCodes'][autocompletewired!='true']", Ele)
    .attr("autocompletewired", "true")
    .autocomplete("/ContentWS/MplaceAnonv2.asmx/ReturnStockCodes", 
    {
    matchSubset:0,
    width:200,
    formatItem:function(row, i, num) {return "    <table class='AutoCompleteStockCode'>" + 
        "<tr>" + 
            "<td style='width:40px'>" +
                "<div><img src='" + row[1] + "' /></div>" + 
            "</td>" + 
            "<td style='text-align:left' class='Result'>" + 
                "<b>" + row[0] + "</b><br />" + row[2] + "<br /><i>" + row[3] + "</i>" + 
            "</td>" + 
        "</tr>" + 
    "</table>";}
    });

    $("[FunctionOnEnter][functionwired!='true']", Ele)
    .attr("functionwired", "true")
    .keypress(function (e) {
                                if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
                                    $(this).blur();
                                    eval($(this).attr("FunctionOnEnter"));   
                                    return false;   
                                } else {   
                                    return true;   
                                }   
                            });

                            $("[IDOfControlToFireOnclickOnEnter][idfunctionwired!='true']", Ele)
    .attr("idfunctionwired", "true")
    .keypress(function(e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            $(this).blur();
            //first, try the standard click call
            try {
                $("#" + $(this).attr("IDOfControlToFireOnclickOnEnter")).fireEvent('onclick');
            }
            catch (e) {
                $("#" + $(this).attr("IDOfControlToFireOnclickOnEnter")).focus();
                $("#" + $(this).attr("IDOfControlToFireOnclickOnEnter")).click();
            }
            return false;
        } else {
            return true;
        }
    });


                            $('tr.AlternatingGridRow').filter(':even').addClass('EvenGridRow').end().filter(':odd').addClass('OddGridRow');
}

function AddDebugText(txt)
{
    if (DebugOn)
    {
            document.getElementById("spnDebug").innerHTML += txt + "<br>";
    }
}

//obtained from http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function MyTip(str)
{
    Tip(str, BALLOON, true, BALLOONIMGPATH, '/imagesv2/tip_balloon/', WIDTH, 200, CENTERMOUSE, true);
}

function MyUnTip()
{
    UnTip();
}

function DHTMLInit() {
    HTTPRequestGlobalReturnFunctionToCall = HTTPRequestGlobalReturnFunction;
}

if (typeof (Sys) !== 'undefined') 
{
    Sys.Application.notifyScriptLoaded();
}

