// Intellectual property of FreshStyle Web and Media 2008. www.FreshStyle.com.au

function replaceSyntax(strString)
{
    return strString.replace(/'/g, "\'").replace(/"/g, "\"");
}

function IsNumeric(strString)
//  check for valid numeric strings	
{
   var strValidChars = "0123456789.-";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
}

function ClearField(thisField, strClearText)		// Clear the field by grabing the object calling this function and its default value to be cleared
{
	if (thisField.value == strClearText)
	{
		thisField.value = ""; thisField.focus();
	}
}

function refreshTable(strTable)
{
    var table = document.getElementById(strTable);
    var tableDnD = new TableDnD();
    // Redefine the findDropTargetRow to put some debug information in
    tableDnD.findDropTargetRow = function(y) {
        var rows = this.table.tBodies[0].rows;
	    var debugStr = "y is "+y+"<br>";
        for (var i=0; i<rows.length; i++) {
            var row = rows[i];
            var rowY    = this.getPosition(row).y;
            var rowHeight = parseInt(row.offsetHeight)/2;
		    if (row.offsetHeight == 0) {
			    rowY = this.getPosition(row.firstChild).y;
			    rowHeight = parseInt(row.firstChild.offsetHeight)/2;
		    }
		    debugStr += "row["+i+"] between "+(rowY-rowHeight)+' and '+(rowY+rowHeight)+"<br>";
            // Because we always have to insert before, we need to offset the height a bit
            if ((y > rowY - rowHeight) && (y < (rowY + rowHeight))) {
                // that's the row we're over
			    //document.getElementById('debug').innerHTML = debugStr+"found row";
                return row;
            }
        }
	    //document.getElementById('debug').innerHTML = debugStr+"no matching row";
        return null;
    }
    // Redefine the onDrop so that we can display something
    tableDnD.onDrop = function(table, row) {
        //strQIDs = '||';     // this will rewrite the ID list from sorting order instead so when building the list, its ordered correctly
    	if (table.id == 'tblImages')
	    {
	        strImages = '||';
	    }
	    
        var rows = this.table.tBodies[0].rows;

        for (var i=0; i<rows.length; i++) {
            //strQIDs += rows[i].id.replace('trQuestionAdded_', '') + '||';
            //document.forms.ppForm.QuestionIDs.value = strQIDs;
		    //debugStr += rows[i].id+" ";
		    if (table.id == 'tblImages')
		    {
                strImages += rows[i].id.replace('trDynamicImage_', '') + '||';
		    }
	    }
	    //document.getElementById('debug').innerHTML = 'row['+row.id+'] dropped<br>'+debugStr;
    }
    tableDnD.init(table);
}

function sortSet(strTable)
{
    var objTable; var objTR;

    // first off kill the current table for sorting
    if (strCurrentTableForSorting != '')
    {
        objTable = document.getElementById(strCurrentTableForSorting);
        objTable.style.border = '1px solid transparent';
        objTable.style.cursor = 'pointer';
        
        for (var i = 0; i < objTable.rows.length; i++)
        {
            objTable.rows[i].style.cursor = 'default';
        }
    }

    // then get the new table for sorting
    objTable = document.getElementById(strTable);

    strCurrentTableForSorting = strTable;

    objTable.style.border = '1px dashed #CCCCCC';

    refreshTable(strTable);
}

function setParent (strFormName, strTable, strValueHolder, strRowID, intValue, strAction)
{
    var objTable = document.getElementById (strTable);

    if(strFormName != '' && strFormName != undefined) { eval('document.forms.' + strFormName + '.' + strValueHolder + '.value = intValue'); }
    else { eval('document.forms[0].' + strValueHolder + '.value = intValue'); }
    
    for (var i = 0; i < objTable.rows.length; i++)
    {
        if (objTable.rows[i].id == strRowID + intValue)
        {
            objTable.rows[i].style.backgroundColor = '#EFEFEF';
            document.getElementById ('spanParentLevel').innerHTML = ARParentLevels[intValue];
        }
        else
        {
            objTable.rows[i].style.backgroundColor = '#FFFFFF';
        }
    }
    if(strAction != undefined) { eval(strAction); }
}

function listAddTo(strType, strValue, intNoDuplicates)
{
    var strCollection = eval('str' + strType);
    if(intNoDuplicates == 1)
    {
        if (strCollection.indexOf('||' + strValue + '||') > -1)
        {
            alert("No duplicate values allowed.");
            return;
        }
    }

    strCollection += strValue + '||';

    listAssignValue(strType, strCollection);

    //try { document.getElementById('Image_' + strImage).style.backgroundColor = '#f9f7c4'; }
    //catch (err) { }

    listBuild(strType);
}

function listEdit(strType, intID, objValue)
{
    var strCollection = eval('str' + strType);
    var ARValues = strCollection.split('||');
    strCollection = '||';

    for(var i = 1; i < (ARValues.length-1); i++)
    {
        if (i == intID)
        {
            strCollection += replaceSyntax(objValue.value) + '||';
        }
        else
        {
            strCollection += ARValues[i] + '||';
        }
    }

    //strCollection = strCollection.replace('||' + strValue + '||', '||');

    //try { document.getElementById('Image_' + strImage).style.backgroundColor = '#FFFFFF'; }
    //catch (err) { }

    listAssignValue(strType, strCollection);

    listBuild(strType);
}

function listDelFrom(strType, intID)
{
    var strCollection = eval('str' + strType);
    var ARValues = strCollection.split('||');
    strCollection = '||';

    for(var i = 1; i < (ARValues.length-1); i++)
    {
        if (i != intID)
        {
            strCollection += ARValues[i] + '||';
        }
    }

    //strCollection = strCollection.replace('||' + strValue + '||', '||');

    //try { document.getElementById('Image_' + strImage).style.backgroundColor = '#FFFFFF'; }
    //catch (err) { }

    listAssignValue(strType, strCollection);

    listBuild(strType);
}

function listBuild(strType)
{
    var strList = '';
    var strListPanel = '';
    var ARValues = eval('str' + strType).split('||');

    //document.getElementById('divList_' + strType).style.display = 'none';

    for (var i = 1; i < (ARValues.length - 1); i++)
    {
        strList = strList + '<tr id="trList_' + strType + '_' + replaceSyntax(ARValues[i]) + '" onClick="refreshTable(\'tblList_' + strType + '\');">';
        strList += listBuildContent(strType, i);
        strList = strList + '</tr>';
    }

    // this is the panel which holds the Module rows... hence append list to this string (last line)
    strListPanel = strListPanel + '<table id="tblList_' + strType + '" cellpadding="0" cellspacing="0" border="0">' + strList + '</table>';

    document.getElementById('divList_' + strType).innerHTML = strListPanel;

    //document.forms[0].Images.value = strImages;

    refreshTable('tblList_' + strType);

    //animatedcollapse.show('divList_' + strType);
}

function addValueToList(strType, intNoDuplicates)
{
    if(intNoDuplicates == undefined) { intNoDuplicates = 1; }
    var objInput = document.getElementById('add' + strType);
    if(objInput.value != '')
    {
        var strValue = objInput.value.replace(/'/g, "\'");
        objInput.value = ''; objInput.focus();
        listAddTo(strType, strValue, intNoDuplicates);
    }
}

function addImage(strForm, strImage)
{
    if (strImages.indexOf('||' + strImage + '||') > -1)
    {
        //alert("This Image has already been assigned!");
        return;
    }

    strImages += strImage + '||';

    try { document.getElementById('Image_' + strImage).style.backgroundColor = '#f9f7c4'; }
    catch (err) { }

    buildImages(strForm);
}

function delImage(strForm, strImage)
{
    //var ARImages = strImages.split('||');

    strImages = strImages.replace('||' + strImage + '||', '||');

    try { document.getElementById('Image_' + strImage).style.backgroundColor = '#FFFFFF'; }
    catch (err) { }

    buildImages(strForm);
}

function buildImages(strForm)
{
    var strList = '';
    var strListPanel = '';
    var ARImages = strImages.split('||');

    for (var i = 1; i < (ARImages.length - 1); i++)
    {
        strList = strList + '<tr id="trDynamicImage_' + ARImages[i] + '">';
        strList = strList + '   <td style="width: 1px; cursor: pointer; padding: 2px 10px 2px 0px;" onClick="delImage(\'AddBusiness\', \'' + ARImages[i] + '\');"><img src="' + strImagesPath + 'admin/icons/invalid.gif" border="0" alt="remove from selection"></td>';
        strList = strList + '   <td style="padding: 2px 10px 2px 0px;">' + ARImages[i] + '</td>';
        strList = strList + '   <td style="width: 1px; cursor: help; padding: 2px 0px 2px 0px;" onClick="previewImage(\'' + ARImages[i] + '\', \'' + strSection + '\');"><img src="' + strImagesPath + 'admin/icons/preview.gif" border="0"></td>';
        strList = strList + '</tr>';
        try { document.getElementById('Image_' + ARImages[i]).style.backgroundColor = '#f9f7c4'; }
        catch (err) { }
    }

    // this is the panel which holds the Module rows... hence append list to this string (last line)
    strListPanel = strListPanel + '<table id="tblImages" width="233" cellpadding="0" cellspacing="0" border="0">' + strList + '</table>';

    document.getElementById('divImages').innerHTML = strListPanel;

    eval('document.forms.' + strForm + '.Images.value = strImages');

    refreshTable('tblImages');
}


function previewImage(strImage, strType)
{
    var objDiv = document.getElementById ('divImagePreview');
    var objImage = document.getElementById ('imgPreview');
    var objSpan = document.getElementById('spanPreview');
    
    if (strImage == null || strImage == undefined)
    {
        objDiv.style.display = 'none';
    }
    else
    {
        if(strSectionImagesPath != '') { strType = strSectionImagesPath; }
        objSpan.innerHTML = strImage;
        objImage.src = strSitePath + 'Resources/default.aspx?W=250&H=150&File=' + strType + '/' + strImage;
        objDiv.style.display = 'block';
    }
}

function confirmDelete(strURL)
{
    var objConfirmation = confirm ('Are you sure you wish to delete this record?');
    if (objConfirmation == false)
    {
        return;
    }
    
    document.location = strURL;
}

function loadurl(dest, strAction) {
 try {
   xmlhttp = window.XMLHttpRequest?new XMLHttpRequest():
  		new ActiveXObject("Microsoft.XMLHTTP");
 }
 catch (e) { alert('Your browser does not support XMLHTTP.'); }
 
 xmlhttp.open("GET", dest);
 xmlhttp.send(null);
}

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 '';
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function roundNumber(num, dec)
{
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

function fadeInOut(strObject, dir, speed, c, strType)
{
    var obj = document.getElementById (strObject);
    //var c = 0;

    if(obj.filters)
    {
        obj.style.filter='alpha(opacity='+c+')';
    }
    else
    {
        obj.style.opacity=c/100;
    }

    if(dir=='in')
    { 
        dir1='in';
        if (c == 0) { obj.style.display = 'block'; }
        c++;
    } 
    else
    { 
        dir1='out';
        c--;
    }

    if(c>100)
    {
        c=100;
        // the line below fades out the notification
        if (strType == 'Notification') { setTimeout('fadeInOut(\'' + strObject + '\', \'out\', ' + speed + ', ' + c + ')', 2); }
        return;
    }

    if(c<0)
    {
        c=0;
        obj.style.display = 'none';
        return;
    }

    setTimeout('fadeInOut(\'' + strObject + '\', \'' + dir + '\', ' + speed + ', ' + c + ', \'' + strType + '\')', speed)
}

// Check the Email Address provided via the validateFormFields function
function validateEmailField(email) {
	invalidChars = " /:,;"

	for (i=0; i<invalidChars.length; i++) {
		badChar = invalidChars.charAt(i)
		if (email.indexOf(badChar,0) > -1) {
			return false
		}
	}
	atPos = email.indexOf("@",1)
	if (atPos == -1) {
		return false
	}
	if (email.indexOf("@",atPos+1) != -1) {
		return false
	}
	periodPos = email.indexOf(".",atPos)
	if (periodPos == -1) {
		return false
	}
	if (periodPos+3 > email.length) {
		return false
	}
	return true;
}

function getRadioValue(objRadio)
{
    for(var i = 0; i < objRadio.length; i++)
    {
        if(objRadio[i].checked) { return objRadio[i].value; }
    }
    return '';
}

function getCheckboxValue(objCheckbox)
{
    var strValue = '||';
    for(var i = 0; i < objCheckbox.length; i++)
    {
        if(objCheckbox[i].checked) { strValue += objCheckbox[i].value + '||'; }
    }
    if (strValue == '||') { strValue = ''; }
    return strValue;
}

function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

function closeDHTMLPopUp()
{
    var objDIVBG = document.getElementById('divPopUpBG');
    var objDIVPanel = document.getElementById('divPopUpPanel');
    //animatedcollapse.toggle('divPopUpPanel');
    //setTimeout('animatedcollapse.toggle(\'divPopUpBG\')', 200);
    objDIVBG.style.display = 'none';
    objDIVPanel.style.display = 'none';
    if (strActionAfterDHTMLPopUp != '')
    { eval(strActionAfterDHTMLPopUp); strActionAfterDHTMLPopUp = ''; }
}

function showDHTMLPopUp(intPanelW, intPanelH, strAction)
{
    var intScreenW = 0, intScreenH = 0, intOffsetX = 0, intOffsetY = 0;

     if (document.documentElement) {
         intScreenW = document.documentElement.offsetWidth;
         intScreenH = document.documentElement.offsetHeight;
     } else if (window.innerWidth && window.innerHeight) {
         intScreenW = window.innerWidth;
         intScreenH = window.innerHeight;
     }

    intScreenW = $(window).width();
    intScreenH = $(window).height();
    intOffsetX = f_scrollLeft();
    intOffsetY = f_scrollTop();

    var intPageHeight = 0;
    intPageHeight = $(document).height();
    //if (intPageHeight == 0 || intPageHeight == '') { intPageHeight = document.height; }
    
    if (intScreenH >= intPageHeight) { intPageHeight = intScreenH; }

    var objDIVBG = document.getElementById('divPopUpBG');
    var objDIVPanel = document.getElementById('divPopUpPanel');

    objDIVBG.style.height = intPageHeight + 'px';
    objDIVPanel.style.left = ((intScreenW - intPanelW) / 2) + 'px';
    objDIVPanel.style.top = ((((intScreenH - intPanelH) / 2)) + intOffsetY) + 'px';
    objDIVPanel.style.width = intPanelW + 'px';
    objDIVPanel.style.height = intPanelH + 'px';

    if(intPanelH > intScreenH)
    { objDIVPanel.style.top = 0; }

    if (objDIVBG.style.display == '')
    {
        objDIVBG.style.display = 'none';
        objDIVPanel.style.display = 'none';
    }
    else
    {
        objDIVBG.style.display = '';
        objDIVPanel.style.display = '';
        //animatedcollapse.toggle('divPopUpBG');
        if(strAction != undefined) { eval(strAction); }     // run the after validation action if defined in the show popup panel caller function
        //animatedcollapse.toggle('divPopUpPanel');
    }
}

strActionAfterDHTMLPopUp = '';      // define what to action after popup close action

function showValidation(strContent, strElement, strTitle)
{
    if (strTitle == '' || strTitle == undefined) { strTitle = 'Validation Alert!'; }
    setPopUpContent("<img src='" + strImagesPath + "layout/alert.gif' border='0' align='left' style='margin: 0px 10px 0px 0px;' /><div style='padding: 0px 0px 20px 0px; font-size: 18px; color: #FF0000;'>" + strTitle + "</div>" + strContent);
    strActionAfterDHTMLPopUp = 'preselectFieldAfterValidation(\'' + strElement + '\')';
    showDHTMLPopUp(560, 50);
}

function preselectFieldAfterValidation(strElement)
{
    try { document.Registration[strElement].focus(); } catch (err) { try { document.Registration[strElement][0].focus(); } catch(err) { } }
}

function setPopUpContent(strContent)
{
    document.getElementById('spanPopUpPanelContent').innerHTML = strContent;
}

function parseText(text)
{
	text = text.replace(/%/gi, "%25");
	text = text.replace(/ /gi, "%20");
	text = text.replace(/!/gi, "%21");
	text = text.replace(/\"/gi, "%22");
	text = text.replace(/#/gi, "%23");
	text = text.replace(/\$/gi, "%24");
	text = text.replace(/&/gi, "%26");
	text = text.replace(/\'/gi, "%27");
	text = text.replace(/\(/gi, "%28");
	text = text.replace(/\)/gi, "%29");
	text = text.replace(/\*/gi, "%2a");
	text = text.replace(/\+/gi, "%2b");
	text = text.replace(/\,/gi, "%2c");
	text = text.replace(/-/gi, "%2d");
	text = text.replace(/\./gi, "%2e");
	text = text.replace(/\//gi, "%2f");
	text = text.replace(/:/gi, "%3a");
	text = text.replace(/;/gi, "%3b");
	text = text.replace(/</gi, "%3c");
	text = text.replace(/=/gi, "%3d");
	text = text.replace(/>/gi, "%3e");
	text = text.replace(/\?/gi, "%3f");
	text = text.replace(/@/gi, "%40");
	text = text.replace(/\[/gi, "%5b");
	text = text.replace(/\\/gi, "%5c");
	text = text.replace(/\]/gi, "%5d");
	text = text.replace(/\^/gi, "%5e");
	text = text.replace(/_/gi, "%5f");
	text = text.replace(/`/gi, "%60");
	text = text.replace(/\{/gi, "%7b");
	text = text.replace(/\|/gi, "%7c");
	text = text.replace(/\}/gi, "%7d");
	text = text.replace(/~/gi, "%7e");
	return text;
} // by Darko G.

function AJAXLoading(strAction)
{
    var objDiv = document.getElementById('divAjaxLoading');
    if(strAction == 'show')
    { objDiv.style.display = ''; }
    else if (strAction == 'hide')
    { objDiv.style.display = 'none'; }
    else
    {
        if (objDiv.style.display == '')
        { objDiv.style.display = 'none'; }
        else
        { objDiv.style.display = ''; }
    }
    objDiv.style.top = (intMouseY + 10) + 'px';
    objDiv.style.left = (intMouseX + 10) + 'px';
} // by Darko G.

function countCharacters(objInput, strShowIn) { document.getElementById(strShowIn).innerHTML = objInput.value.length; }