// Define WSI object
var WSI={
	formname: null,
	errordiv: null,
	dartTag: null,
	icrossingTag: null,
	dotomiTag: null

};

WSI.setProps=function(formName, dartTag, icrossingTag, dotomiTransactionFlag, cliPromoId, pageName, siteFlag) {
	this.formname = formName;
	this.errordiv = formName + "error";
	this.dartTag = dartTag;
	this.icrossingTag = icrossingTag;
	if (dotomiTransactionFlag == 'true') {
		WSI.dotomiTag = WSI.buildDotomiTag(cliPromoId, pageName, siteFlag);
	}
}

WSI.buildDotomiTag=function(cliPromoId, pageName, siteFlag) {
	
	var dtmSrc = window.location.protocol + "//login.dotomi.com/ucm/UCMController?"+
	"dtm_com=29&dtm_fid=102&dtm_cid=2390&dtm_cmagic=999600&dtm_format=5";

	var dtmTag = new Array();
	/* custom fields SUBSTITUTE DYNAMIC VALUES ONLY IN THIS BLOCK */
	dtmTag.cli_promo_id = cliPromoId;
	dtmTag.dtmc_event_name = pageName;
	dtmTag.dtmc_site_flag = siteFlag;
	/* custom fields end */
	
	dtmTag.dtmc_loc = document.location.href;
	dtmTag.dtmc_ref = document.referrer;
	for (var item in dtmTag){
		if(typeof dtmTag[item] != "function" && typeof dtmTag[item] != "object")
			dtmSrc += "&" + item + "=" + escape(dtmTag[item]);
	}   
	setTimeout('timeOutDotomiTrans()',5000);
	return '<div id="dtmdivtrans" style="display:none;">' +
	'<iframe name="response_frame" src="' + dtmSrc + '"></iframe></div>';
	
	
}

function timeOutDotomiTrans() { document.getElementById("dtmdivtrans").innerHTML = "";}

// define success callback
WSI.submitCallbackSuccess=function(obj){
	if (typeof obj === 'object'){
		// Process JSON object response
		if (obj.success){
			
			// Success
			$("form[name='"+WSI.formname+"']").find('fieldset').slideUp().end().find('h2').text(obj.success).fadeTo('normal', 1);
			WSI.icrossingAppend();
			WSI.dartAppend();
			WSI.dotomiAppend();
		} else if (obj.errors) {
			var errorMessage='';
			// Errors
			$("form[name='" + WSI.formname+"'] label").removeClass("error");

			$.each(obj.errors, function(err){
				// add error class to field
				$("form[name='"+WSI.formname+"'] label[for='"+obj.errors[err].field+"']").addClass("error");
				// add error message
				errorMessage = errorMessage + obj.errors[err].error + '<br/>';
			});
			// Display errors
			$("#"+WSI.errordiv).html(errorMessage);

			// Re-enable submit button and fade in
			$("form[name='"+WSI.formname+"']").find("input").removeAttr("disabled").end().children().fadeTo('normal', 1);

		} else {
			// The object is not what we expect
			WSI.submitCallbackFailure(null, 'An error occured', null);
		}
	} else {
		// We have a bad response
		WSI.submitCallbackFailure(null, 'An error occured', null);
	}
};

// define failure callback
WSI.submitCallbackFailure=function(XMLHttpRequest, textStatus, errorThrown){
	//Record error
	$("#"+WSI.errordiv).html("Error: "+ textStatus + "<div>Please try again</div>");

	// Re-enable submit button and fade in
	$("form[name='"+WSI.formname+"']").find("input").removeAttr("disabled").end().children().fadeTo('normal', 1);
};

WSI.salesforce={};

//define success callback
WSI.salesforce.submitCallbackSuccess=function(obj){
	if (typeof obj === 'object'){
		// Process JSON object response
		if (obj.success){
			// Success
			// 1. fade in fields
			// 2. Attach print message
			$("form[name='" + WSI.formname+"'] label").removeClass("error");
			$("form[name='"+WSI.formname+"']").children().fadeTo('normal', 1).end();
			// $("form[name='"+WSI.formname+"']").find('fieldset').slideUp().end().find('h2.success').text(obj.success).fadeTo('normal', 1);
			$("input[title='Print']").removeAttr("disabled");
			$("input[title!='Print'], select").addClass("disable").attr("readonly", "readonly").removeAttr("disabled");
			window.scrollTo(0, 0);
			WSI.icrossingAppend();
			WSI.dartAppend();
			WSI.dotomiAppend();
			WSI.salesforce.init();
			WSI.salesforce.printOpen();
		} else if (obj.errors) {
			var errorMessage='';
			$("form[name='" + WSI.formname+"'] label").removeClass("error");

			// Errors
			$.each(obj.errors, function(err){
				// add error class to field
				$("form[name='"+WSI.formname+"'] label[for='"+obj.errors[err].field+"']").addClass("error");
				// add error message
				errorMessage = errorMessage + obj.errors[err].error + '<br/>';
			});
			// Display errors
			$(".errors").html(errorMessage);

			// Re-enable submit button and fade in
			$("form[name='"+WSI.formname+"']").find("input").removeAttr("disabled").end().children().fadeTo('normal', 1);

		} else {
			// The object is not what we expect
			WSI.salesforce.submitCallbackFailure(null, 'An error occured', null);
		}
	} else {
		// We have a bad response
		WSI.submitCallbackFailure(null, 'An error occured', null);
	}
};

//define failure callback
WSI.salesforce.submitCallbackFailure=function(XMLHttpRequest, textStatus, errorThrown){
	//Record error
	$(".errors").html("Error: "+ textStatus + "<div>Please try again</div>");

	// Re-enable submit button and fade in
	$("form[name='"+WSI.formname+"']").find("input").removeAttr("disabled").end().children().fadeTo('normal', 1);
};

// Define print dialog open
WSI.salesforce.printOpen=function(){
	// Set the window id
	var dlg=$("#printDialog .window");

	// JS for the window
	var maskHeight = $(document).height();  
	var maskWidth = $(window).width();  

	// Get the mask
	var mask = $('#printDialogMask');
	//Set height and width to mask to fill up the whole screen  
	mask.css({'width':maskWidth,'height':maskHeight, 'filter': 'alpha(opacity=50)'}).fadeIn(1000);  
          
	//Get the window height and width  
	var winH = $(window).height();  
	var winW = $(window).width();  

	//Set the popup window to center  
	dlg.css({'top': winH/2-dlg.height()/2, 'left': winW/2-dlg.width()/2}).fadeIn(2000);

}

// Define print function
WSI.salesforce.print=function(){
	$('#printDialogMask, #printDialog .window').hide();  		
	window.print();
	return false;
}

// Define close function
WSI.salesforce.close=function(){
    $('#printDialogMask, #printDialog .window').hide();         
    window.parent.location.reload()
    return false;
}

// Define Salesforce init()
WSI.salesforce.init=function(){
    if(WSI.formname == 'registerform') {
    	$("body").append('<div id="printDialog"><div class="window"><div id="printMessage" class="printMessage">Thank you for registering for more information, a representative will contact you shortly to answer any questions you may have about our programs. In the meantime, browse our business solutions at <br><a href="http://www.wsiforyourbusiness.com">www.wsiforyourbusiness.com</a></div><a href="#" id="printLink"><img src="/apps/designer/docroot/images/btn_close.gif" tile="Close" alt="Close"></a></div><div id="printDialogMask"></div></div>').find("#printLink").click(WSI.salesforce.close);
    } else {
        $("body").append('<div id="printDialog"><div class="window"><div id="printMessage" class="printMessage">Thank You for submitting your information. Please print out your application by clicking the "Print Application" button below. Then fax it along with your qualifications to (702)&nbsp;360-7171.</div><a href="#" id="printLink"><img src="/apps/designer/docroot/images/btn_print_small.gif" tile="Print" alt="Print"></a></div><div id="printDialogMask"></div></div>').find("#printLink").click(WSI.salesforce.print);
    }
}

//set pixel icon for Merchantize tracking
WSI.icrossingAppend=function(){
	if (WSI.icrossingTag != null && WSI.icrossingTag != '') {
		$("body").append(WSI.icrossingTag);
	}
}

WSI.dartAppend=function(){
	if (WSI.dartTag != null && WSI.dartTag != '') {
		$("body").append(WSI.dartTag);
	}
}


WSI.dotomiAppend=function(){
	if (WSI.dotomiTag != null && WSI.dotomiTag != '') {
		$("body").append(WSI.dotomiTag);
	}
}




function attachSalesforceSubmit(formName, dartTag, icrossingTag, dotomiFlag, cliPromoId, pageName, siteFlag) {
	$("form[name='"+formName+"']").submit(function(evt){
		// Has this been successfully submitted? If so print
		if ($('#salesforce-success').length > 0){window.print(); return false;}
		// Clear errors
		$(".errors").html('');
		// Grab form inputs and post via AJAX
		var params=$("form[name='"+formName+"']").serialize();

		WSI.setProps(formName, dartTag, icrossingTag, dotomiFlag, cliPromoId, pageName, siteFlag);
		// Disable submit and partially fade form
		$("input", this).attr("disabled", "disabled").removeClass("error").end().children().fadeTo('normal', .33);
		$.ajax( {'type':'POST', 'url': this.action, 'dataType': 'json', 'data': params, 'success': WSI.salesforce.submitCallbackSuccess, 'error': WSI.salesforce.submitCallbackFailure} );
		return false;
	});
	// Create print dialog
	WSI.salesforce.init();
}

function attachFormSubmit(formName, dartTag, icrossingTag, dotomiTransactionFlag, cliPromoId, pageName, siteFlag) {
	$("form[name='"+formName+"']").submit(function(evt){
	 // Clear errors
		 $("#"+formName+"error").html('');
		 // Grab form inputs and post via AJAX
		 var params=$("form[name='"+formName+"']").serialize();

		WSI.setProps(formName, dartTag, icrossingTag, dotomiTransactionFlag, cliPromoId, pageName, siteFlag);

	      // Disable submit and partially fade form
	     $("input", this).attr("disabled", "disabled").removeClass("error").end().children().fadeTo('normal', .33);
	     $.ajax( {'type':'POST', 'url': this.action, 'dataType': 'json', 'data': params, 'success': WSI.submitCallbackSuccess, 'error': WSI.submitCallbackFailure} );
	    return false;
	});
}

