﻿function globalInit() {
	updateButtons();
	jQuery('.input-select').each(function() {
		fVal = jQuery(this).attr('selected');
		if (fVal != '') {
			jQuery(this).val(fVal);
		}
	});
	
	jQuery('.input-radio').each(function() {
		fVal = jQuery(this).attr('selected');
		fValue = jQuery(this).attr('value');
		
		if (fVal != undefined) {
			if (fVal.toUpperCase() == fValue.toUpperCase()) {
				jQuery(this).attr('checked', 'true');
			} else {
				jQuery(this).attr('checked', 'false');
			}
		}
	});

	jQuery('.input-time').each(function() {
		jQuery(this).timeEntry();
		jQuery(this).removeClass('input-time');
	});

	jQuery('.champ-header').each(function () {
		jQuery(this).addClass('ui-toolbar');
		jQuery(this).addClass('ui-widget-header');
		jQuery(this).addClass('ui-helper-clearfix');
		jQuery(this).addClass('ui-corner-all');
		jQuery(this).css({
			'padding': '5px'
		});
		jQuery(this).removeClass('champ-header');
	});

	try {
		top.disableLoader();
	} catch (e) {
	}
}

jQuery(function () {
	/*
	if (msie || isIOS()) {
	$.fx.off = true;
	}
	*/
	globalInit();

	if (typeof window.pageInit == 'function') {
		pageInit();
	}

	if (typeof window.init == 'function') {
		init();
	}

	if (typeof window.initUploader == 'function') {
		initUploader();
	}

	fSPID = request("SPID")
	if (fSPID == undefined) {
		fSPID = 'nospid';
	}
	fID = request("LINKID")
	if (fID == undefined) {
		fID = 0;
	}

	if (document.getElementById('appInitDescription-' + fSPID + fID)) {
		fFunc = eval(jQuery('#appInitDescription-' + fSPID + fID).html());
		fFunc(fID, fSPID);
	}

	fBoxCNT = 0

	jQuery('.input-date').datepicker();

	ui();

	initAccordions();

	jQuery('.dialog').each(function () {
		fName = jQuery(this).attr('name');
		//fButton1 = jQuery(this).attr('button1');
		//fButton2 = jQuery(this).attr('button2');
		//fButton3 = jQuery(this).attr('button3');

		jQuery(this).dialog({
			autoOpen: false,
			width: 600,
			title: fName,
			buttons: {
				"Close": function () {
					jQuery(this).dialog("close");
				}
			}
		});
		jQuery(this).removeClass('dialog');
	});

	jQuery('.wizardbox').each(function () {
		fName = jQuery(this).attr('name');
		//fButton1 = jQuery(this).attr('button1');
		//fButton2 = jQuery(this).attr('button2');
		//fButton3 = jQuery(this).attr('button3');

		jQuery(this).dialog({
			autoOpen: false,
			width: 600,
			title: fName,
			buttons: {
				"Cancel": function () {
					jQuery(this).dialog("close");
				},
				"Finish": function () {
					jQuery(this).dialog("close");
				},
				"Next": function () {
					jQuery(this).dialog("close");
				},
				"Previous": function () {
					jQuery(this).dialog("close");
				}
			}
		});
	});

	initTabs();


	initUploaders();

	jQuery('img').each(function () {
		fSrc = jQuery(this).attr('src');
		if (fSrc == '') {
			jQuery(this).attr('src', '/net/images/spacer.gif');
		}
	});

	try {
		initDataTables();
	} catch (e) {
	}

	jQuery('.overlay').each(function (i) {
		jQuery(this).overlay({
			mask: {
				color: '#fff',
				loadSpeed: 200,
				opacity: 0.5
			},
			closeOnClick: true,
			fixed: false,
			load: false
		});
	});

	initHelper();
	initColorInputs();
	//initHTMLEditors();

	if (top.document.getElementById('loader')) {
		top.document.getElementById('loader').style.display = 'none';
	}

	if (document.getElementById('name')) {
		document.getElementById('name').select();
	}

	try {
		initCK();
	} catch (e) {
	}

	setupErrorHandler();

});

function initAccordions() {
	jQuery(".accordion").accordion({
		header : "h3",
		autoHeight : false,
		collapsible : true,
		animated : "bounceslide",
		icons : {
			'header' : 'ui-icon-circle-arrow-e',
			'headerSelected' : 'ui-icon-circle-arrow-s'
		}
	});
}

function initTabs() {
	jQuery(".tabs").tabs();
}

function genericUploadHandler(fResponse) {
	
	fArray = fResponse.split('|');
	fField = fArray[0];
	fIsSrc = fArray[1];
	fData = fArray[2];
	
	if (fIsSrc == '0') {
		jQuery('#'+fField).html(fData);
	} else {
		jQuery('#'+fField).attr('src', fData);
	}

	return true;
}

function replace(origString, inChar, outChar) {
	var newString = origString.split(inChar);
	newString = newString.join(outChar);
	return newString;
}

function replaceLast(origString, inChar, outChar) {
	newString = '';
	var fArray = origString.split(inChar);
	for (i=0; i<fArray.length; i++) {
		newString += fArray[i]
		if (i<fArray.length-2) {
			newString += inChar;
		}
	}
	return newString;
}

function getRandomNumber(fMax) {
	return Math.floor(Math.random()*(fMax+1))
}



function initUploaders() {
	jQuery('.input-file').each(function () {
		fID = jQuery(this).attr('id');
		fName = jQuery(this).attr('name');
		fURL = jQuery(this).attr('url');
		fSizeLimit = jQuery(this).attr('sizelimit');
		fMulti = jQuery(this).attr('multi');
		fLabel = jQuery(this).attr('label');
		fAuto = jQuery(this).attr('auto');
		fWidth = jQuery(this).attr('width');
		if (fLabel == undefined || fLabel == '') {
			fLabel = 'Upload File...';
		}

		if (fLabel == 'none') {
			fHideButton = true;
		} else {
			fHideButton = false;
		}

		if (fWidth == undefined || fWidth == '') {
			fWidth = 110;
		}

		if (fName == undefined || fName == '') {
			/* Generate a random NAME if necessary */
			fName = 'FILE' + getRandomNumber(1000000);
		}
		fQueueName = fName + 'Queue';

		if (fID == '' || fID == undefined) {
			/* The file field requires an ID - so put it in if necessary */
			jQuery(this).attr('id', fName);
		}

		if (document.getElementById(fQueueName)) {
			//
		} else {
			/* Create the Queue div if necessary*/
			jQuery(this).after('<div id="' + fQueueName + '"></div>');
		}

		/* Set the Auto variable */
		if (fAuto != undefined) {
			fAuto.toLowerCase();
		}
		switch (fAuto) {
			case 'false':
				fAuto = false;
				break;
			case '0':
				fAuto = false;
				break;
			case 'no':
				fAuto = false;
				break;
			default:
				fAuto = true;
				break;
		}

		/* Set the Multi variable */
		if (fMulti != undefined) {
			fMulti.toLowerCase();
		}
		switch (fMulti) {
			case 'true':
				fMulti = true;
				break;
			case '1':
				fMulti = true;
				break;
			case 'yes':
				fMulti = true;
				break;
			default:
				fMulti = false;
				break;
		}

		if (fMulti == true) {
			jQuery(this).uploadify({
				'uploader': '/js/uploadify/uploadify.swf',
				'script': escape(fURL),
				'fileDataName': fName,
				'cancelImg': '/js/uploadify/cancel.png',
				'folder': '/files/temp',
				'queueID': fQueueName,
				'queueSizeLimit': fSizeLimit,
				'buttonText': fLabel,
				'auto': fAuto,
				'multi': fMulti,
				'wmode': 'transparent',
				'hideButton': fHideButton,
				'width': fWidth,
				'onError': function (fEvent, fID, fFileObj, fErrorObj) {
					$.post('/net/remote/error/?action=notify', {
						'BODY': 'type: ' + fErrorObj.type + '<br>info: ' + fErrorObj.info
					}, function (data) {
					});
					return true;
				},
				'onComplete': function (event, queueID, fileObj, response, data) {
					fCallBack = jQuery(event.target).attr('callback-single');
					if (fCallBack != '' && fCallBack != undefined) {
						fCallBack = eval(fCallBack);
						return fCallBack(response, queueID, event, data);
					}
				},
				'onAllComplete': function (event, data) {
					fCallBack = jQuery(event.target).attr('callback');
					if (fCallBack != '' && fCallBack != undefined) {
						fCallBack = eval(fCallBack);
						return fCallBack('OK');
					} else {
						return genericUploadHandler('OK');
					}
				}

			});
		} else {
			jQuery(this).uploadify({
				'uploader': '/js/uploadify/uploadify.swf',
				'script': escape(fURL),
				'fileDataName': fName,
				'cancelImg': '/js/uploadify/cancel.png',
				'folder': '/files/temp',
				'queueID': fQueueName,
				'queueSizeLimit': fSizeLimit,
				'buttonText': fLabel,
				'auto': fAuto,
				'multi': fMulti,
				'wmode': 'transparent',
				'hideButton': fHideButton,
				'width': fWidth,
				'onError': function (fEvent, fID, fFileObj, fErrorObj) {
					$.post('/net/remote/error/?action=notify', {
						'BODY': 'script: ' + fURL + '<br>type: ' + fErrorObj.type + '<br>info: ' + fErrorObj.info
					}, function (data) {
					});
					return true;
				},
				'onComplete': function (event, queueID, fileObj, response, data) {
					fCallBack = jQuery(event.target).attr('callback');
					if (fCallBack != '' && fCallBack != undefined) {
						fCallBack = eval(fCallBack);
						return fCallBack(response, queueID, event, data);
					} else {
						return genericUploadHandler(response, queueID, event);
					}
				}

			});
		}

		jQuery(this).removeClass('input-file');

	});

}

function initHTMLEditors() {
	jQuery('.input-html').each(function(i) {
		fID = jQuery(this).attr('id');
		jQuery('#'+fID).ckeditor(
			function() {
				CKFinder.SetupCKEditor(this);
			}
		);
	});
}

function initHelper() {
	fHelper = jQuery('#helper').detach();
	fHelper.appendTo('body');
	
	jQuery('#helper').dialog({
		autoOpen: false,
		title: 'Help &amp; Tips',
		width: 700,
		buttons: {
			"Ok": function() { 
				jQuery(this).dialog("close"); 
			}
		}
	});
	
	fHelper = jQuery('#helperEditor').detach();
	fHelper.appendTo('body');

	jQuery('#helperEditor').dialog({
		autoOpen: false,
		title: 'Helper Editor',
		width: 700,
		buttons: {
			"Cancel": function() { 
				jQuery(this).dialog("close"); 
			},
			"Save Changes": function() {
				helperUpdate();
			}
		}
	});
	
}

function openHelper() {
	jQuery('#helper').dialog('open');
}

function helperUpdate() {
	fArray = jQuery('#helperEditorForm').serializeArray();
	$.post(window.link+'&spid=helper.update', fArray, function(data) {
		if (data == 'OK') {
			jQuery('#helperEditor').dialog('close');
		} else {
			alert('Error Updating:\n'+data);
		}
	});
}

function editHelper() {
	jQuery('#helperEditor').dialog('open');
}

function initColorInputs() {
	jQuery('.input-color').each(function() {
		fVal = jQuery(this).val();
		fVal = fVal.toLowerCase();
		jQuery(this).val(fVal);
		
		jQuery(this).ColorPicker({
			'color': fVal,
			'onChange': function() {
				jQuery(this).css({
					'background-color': jQuery(this).val()
				})
			}
		});
	});
}

function isIOS() {
	fStatus = false;
	if ($.browser.webkit) {
		fIpad = navigator.userAgent.indexOf('iPad');
		fIphone = navigator.userAgent.indexOf('iPhone');
		if (fIpad > -1 || fIphone > -1) {
			fStatus = true;
		}
	}
	
	return fStatus;
}

function handleIncompatibleIE() {
	jQuery('body').append('<div id="warningIncompatibleBrowser"><h1>Wow, your browser is really old!</h1><div>You are using a browser version that may cause this web page to crash or produce unexpected results.</div><div>Please consider <a href="http://www.microsoft.com/ie" target="_blank">upgrading it</a> or using <a href="http://www.firefox.com" target="_blank">Firefox</a> or <a href="http://www.apple.com/safari" target="_blank">Safari</a>.</div><div><br><input type="button" onclick="jQuery(\'#warningIncompatibleBrowser\').fadeOut(300)" value="Close"></div>');
	jQuery('#warningIncompatibleBrowser').fadeIn(300);
}

function request(ji) {
    hu = window.location.search.substring(1);
    gy = hu.split("&");
    fResult = 1;

    for (i = 0; i < gy.length; i++) {
        ft = gy[i].split("=");
        if (ft[0] == ji) {
            fResult = ft[1];
        }
    }

    return fResult;
}

function fancyboxLoader(fText, fFunc) {
    $.fancybox('<div style="text-align: center; padding: 30px"><h1>' + fText + '...</h1><div style="text-align: center; padding: 10px"><img src="/net/images/loader-yellow.gif"></div></div>', {
        'easingIn': 'swing',
        'easingOut': 'swing',
        'transitionIn': 'easeOutBack',
        'transitionOut': 'easeInBack',
        'speedIn': 400,
        'speedOut': 400,
        'overlayShow': true,
        'autoDimensions': true,
        'hideOnOverlayClick': true,
        'onComplete': function () {
            fFunc();
        }
    });
}

function ui() {
	jQuery('.itembox').each(function() {
		fName = jQuery(this).attr('name');
		fID = 'itembox_'+fBoxCNT;
		jQuery(this).attr('id', fID);
		boxify(fID, fName);
		fBoxCNT++;
		jQuery(this).removeClass('itembox');
	});

    jQuery('.ajax-button').each(function () {
        transformButton(this);
        jQuery(this).removeClass('ajax-button');
    });

    jQuery('.ajax-input').each(function () {
        jQuery(this).addClass('border');
        jQuery(this).addClass('shadow');
        jQuery(this).css({
            'width': 200,
            'padding': '5px'
        });
        jQuery(this).removeClass('ajax-input');
    });

    jQuery('.ajax-textarea').each(function () {
        jQuery(this).addClass('border');
        jQuery(this).addClass('shadow');
        jQuery(this).css({
            'width': 400,
            'padding': '5px'
        });
        jQuery(this).removeClass('ajax-textarea');
    });

    jQuery('.ajax-select').each(function () {
        jQuery(this).addClass('border');
        jQuery(this).addClass('shadow');
        jQuery(this).css({
            'padding': '5px',
            'width': 'auto'
        });
        jQuery(this).removeClass('ajax-select');
       });

	try {
		initDataTables();
	} catch (exception) {
		//
	}
}

function jsTrace(fFunction, fURL, fID, fText) {
	fMsg = 'Function: '+fFunction+'\nURL: '+fURL+'\nID: '+fID+'\nText: '+fText;
   	alert(fMsg);
}

function stringExists(fData, fString) {
	fPos = fData.toUpperCase().indexOf(fString.toUpperCase());
	if (fPos > -1) {
		fResult = true;
	} else {
		fResult = false;
	}
	return fResult;
}

function setupErrorHandler() {
	jQuery(document).ajaxError(function (event, jqxhr, settings, exception) {
		$.post('/net/remote/error/?action=notify', {
			'BODY': '<h1>jQuery Ajax Error in Script</h1>Page: ' + location.href + '<br>Ajax URL: '+settings.url + '<br>STATUS: ' + event.status + '<br>xhr RESPONSE: '+jqxhr.responseText
		}, function (data) {
		});
		return true;
	});
}


