/**
 * Overlib Styling Declarations to allow CSS class override of styles
 *
 */
var ol_fgclass = 'ol-foreground';
var ol_bgclass = 'ol-background';
var ol_textfontclass = 'ol-textfont';
var ol_captionfontclass = 'ol-captionfont';
var ol_closefontclass = 'ol-closefont';
var fetchuid = 0;
var additionaltags = Array();
var additionaltagdata = '';
// general utility for browsing a named array or object
function xshow(o) {
    s = '';
    for (e in o) {
        s += e + '=' + o[e] + '\n';
    }
    alert(s);
}

/**
 * Writes a dynamically generated list
 * @param string The parameters to insert into the <select> tag
 * @param array A javascript array of list options in the form [key,value,text]
 * @param string The key to display for the initial state of the list
 * @param string The original key that was selected
 * @param string The original item value that was selected
 */
function writeDynaList(selectParams, source, key, orig_key, orig_val) {
    var html = '\n	<select ' + selectParams + '>';
    var i = 0;
    for (x in source) {
        if (source[x][0] == key) {
            var selected = '';
            if ((orig_key == key && orig_val == source[x][1]) || (i == 0 && orig_key != key)) {
                selected = 'selected="selected"';
            }
            html += '\n		<option value="' + source[x][1] + '" ' + selected + '>' + source[x][2] + '</option>';
        }
        i++;
    }
    html += '\n	</select>';

    document.writeln(html);
}

/**
 * Changes a dynamically generated list
 * @param string The name of the list to change
 * @param array A javascript array of list options in the form [key,value,text]
 * @param string The key to display
 * @param string The original key that was selected
 * @param string The original item value that was selected
 */
function changeDynaList(listname, source, key, orig_key, orig_val) {
    var list = eval('document.adminForm.' + listname);

    // empty the list
    for (i in list.options.length) {
        list.options[i] = null;
    }
    i = 0;
    for (x in source) {
        if (source[x][0] == key) {
            opt = new Option();
            opt.value = source[x][1];
            opt.text = source[x][2];

            if ((orig_key == key && orig_val == opt.value) || i == 0) {
                opt.selected = true;
            }
            list.options[i++] = opt;
        }
    }
    list.length = i;
}

/**
 * Adds a select item(s) from one list to another
 */
function addSelectedToList(frmName, srcListName, tgtListName) {
    var form = eval('document.' + frmName);
    var srcList = eval('form.' + srcListName);
    var tgtList = eval('form.' + tgtListName);

    var srcLen = srcList.length;
    var tgtLen = tgtList.length;
    var tgt = "x";

    //build array of target items
    for (var i = tgtLen - 1; i > -1; i--) {
        tgt += "," + tgtList.options[i].value + ","
    }

    //Pull selected resources and add them to list
    //for (var i=srcLen-1; i > -1; i--) {
    for (var i = 0; i < srcLen; i++) {
        if (srcList.options[i].selected && tgt.indexOf("," + srcList.options[i].value + ",") == -1) {
            opt = new Option(srcList.options[i].text, srcList.options[i].value);
            tgtList.options[tgtList.length] = opt;
        }
    }
}

function delSelectedFromList(frmName, srcListName) {
    var form = eval('document.' + frmName);
    var srcList = eval('form.' + srcListName);

    var srcLen = srcList.length;

    for (var i = srcLen - 1; i > -1; i--) {
        if (srcList.options[i].selected) {
            srcList.options[i] = null;
        }
    }
}

function moveInList(frmName, srcListName, index, to) {
    var form = eval('document.' + frmName);
    var srcList = eval('form.' + srcListName);
    var total = srcList.options.length - 1;

    if (index == -1) {
        return false;
    }
    if (to == +1 && index == total) {
        return false;
    }
    if (to == -1 && index == 0) {
        return false;
    }

    var items = new Array;
    var values = new Array;

    for (i = total; i >= 0; i--) {
        items[i] = srcList.options[i].text;
        values[i] = srcList.options[i].value;
    }
    for (i = total; i >= 0; i--) {
        if (index == i) {
            srcList.options[i + to] = new Option(items[i], values[i], 0, 1);
            srcList.options[i] = new Option(items[i + to], values[i + to]);
            i--;
        } else {
            srcList.options[i] = new Option(items[i], values[i]);
        }
    }
    srcList.focus();
    return true;
}

function getSelectedOption(frmName, srcListName) {
    var form = eval('document.' + frmName);
    var srcList = eval('form.' + srcListName);

    i = srcList.selectedIndex;
    if (i != null && i > -1) {
        return srcList.options[i];
    } else {
        return null;
    }
}

function setSelectedValue(frmName, srcListName, value) {
    var form = eval('document.' + frmName);
    var srcList = eval('form.' + srcListName);

    var srcLen = srcList.length;

    for (var i = 0; i < srcLen; i++) {
        srcList.options[i].selected = false;
        if (srcList.options[i].value == value) {
            srcList.options[i].selected = true;
        }
    }
}

function getSelectedRadio(frmName, srcGroupName) {
    var form = eval('document.' + frmName);
    var srcGroup = eval('form.' + srcGroupName);

    return radioGetCheckedValue(srcGroup);
}

// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function radioGetCheckedValue(radioObj) {
    if (!radioObj) {
        return '';
    }
    var n = radioObj.length;
    if (n == undefined) {
        if (radioObj.checked) {
            return radioObj.value;
        } else {
            return '';
        }
    }
    for (var i = 0; i < n; i++) {
        if (radioObj[i].checked) {
            return radioObj[i].value;
        }
    }
    return '';
}

function getSelectedValue(frmName, srcListName) {
    var form = eval('document.' + frmName);
    var srcList = eval('form.' + srcListName);

    i = srcList.selectedIndex;
    if (i != null && i > -1) {
        return srcList.options[i].value;
    } else {
        return null;
    }
}

function getSelectedText(frmName, srcListName) {
    var form = eval('document.' + frmName);
    var srcList = eval('form.' + srcListName);

    i = srcList.selectedIndex;
    if (i != null && i > -1) {
        return srcList.options[i].text;
    } else {
        return null;
    }
}

function chgSelectedValue(frmName, srcListName, value) {
    var form = eval('document.' + frmName);
    var srcList = eval('form.' + srcListName);

    i = srcList.selectedIndex;
    if (i != null && i > -1) {
        srcList.options[i].value = value;
        return true;
    } else {
        return false;
    }
}

/**
 * Toggles the check state of a group of boxes
 *
 * Checkboxes must have an id attribute in the form cb0, cb1...
 * @param The number of box to 'check'
 * @param An alternative field name
 */
function checkAll(n, fldName) {
    if (!fldName) {
        fldName = 'cb';
    }
   
    
    var f = document.adminForm;
    var c = f.toggle.checked;
    
    var n2 = 0;
    for (i = 0; i < n; i++) {
        cb = eval('f.' + fldName + '' + i);
        if (cb) {
            cb.checked = c;
            n2++;
        }
    }
    if (c) {
        document.adminForm.boxchecked.value = n2;
    } else {
        document.adminForm.boxchecked.value = 0;
    }
}

function listItemTask(id, task) {
    var f = document.adminForm;
    cb = eval('f.' + id);
    if (cb) {
        for (i = 0; true; i++) {
            cbx = eval('f.cb' + i);
            if (!cbx) break;
            cbx.checked = false;
        } // for
        cb.checked = true;
        f.boxchecked.value = 1;
        submitbutton(task);
        f.task.value = '';
    }
    return false;
}

function hideMainMenu() {
    if (document.adminForm.hidemainmenu) {
        document.adminForm.hidemainmenu.value = 1;
    }
}

function isChecked(isitchecked) {
    if (isitchecked == true) {
        document.adminForm.boxchecked.value++;
    } else {
        document.adminForm.boxchecked.value--;
    }
}

/**
 * Default function.  Usually would be overriden by the component
 */
function submitbutton(pressbutton, itemId) {

    submitform(pressbutton, itemId);
}

/**
 * Submit the admin form
 */
function submitform(pressbutton, itemId) {

    if (pressbutton) {
        document.adminForm.task.value = pressbutton;

    }
    if (itemId) {
        document.adminForm.itemId.value = itemId;

    }
    if (typeof document.adminForm.onsubmit == "function") {

        document.adminForm.onsubmit();
    }

    document.adminForm.submit();
    document.adminForm.task.value = '';
}


function submitform2(pressbutton, itemId) {

    if (pressbutton) {
        document.adminForm2.task.value = pressbutton;

    }
    if (itemId) {
        document.adminForm2.itemId.value = itemId;

    }
    if (typeof document.adminForm2.onsubmit == "function") {

        document.adminForm2.onsubmit();
    }

    document.adminForm2.submit();
    document.adminForm2.task.value = '';
}

/**
 * Submit the control panel admin form
 */
function submitcpform(sectionid, id) {
    document.adminForm.sectionid.value = sectionid;
    document.adminForm.id.value = id;
    submitbutton("edit");
}

/**
 * Getting radio button that is selected.
 */
function getSelected(allbuttons) {
    for (i = 0; i < allbuttons.length; i++) {
        if (allbuttons[i].checked) {
            return allbuttons[i].value
        }
    }
    return null;
}

// JS Calendar
var calendar = null; // remember the calendar object so that we reuse
// it and avoid creating another

// This function gets called when an end-user clicks on some date
function selected(cal, date) {
    cal.sel.value = date; // just update the value of the input field
}

// And this gets called when the end-user clicks on the _selected_ date,
// or clicks the "Close" (X) button.  It just hides the calendar without
// destroying it.
function closeHandler(cal) {
    cal.hide();			// hide the calendar

    // don't check mousedown on document anymore (used to be able to hide the
    // calendar when someone clicks outside it, see the showCalendar function).
    Calendar.removeEvent(document, "mousedown", checkCalendar);
}

// This gets called when the user presses a mouse button anywhere in the
// document, if the calendar is shown.  If the click was outside the open
// calendar this function closes it.
function checkCalendar(ev) {
    var el = Calendar.is_ie ? Calendar.getElement(ev) : Calendar.getTargetElement(ev);
    for (; el != null; el = el.parentNode)
        // FIXME: allow end-user to click some link without closing the
        // calendar.  Good to see real-time stylesheet change :)
        if (el == calendar.element || el.tagName == "A") break;
    if (el == null) {
        // calls closeHandler which should hide the calendar.
        calendar.callCloseHandler();
        Calendar.stopEvent(ev);
    }
}

// This function shows the calendar under the element having the given id.
// It takes care of catching "mousedown" signals on document and hiding the
// calendar if the click was outside.
function showCalendar(id, dateFormat) {
    var el = document.getElementById(id);
    if (calendar != null) {
        // we already have one created, so just update it.
        calendar.hide();		// hide the existing calendar
        calendar.parseDate(el.value); // set it to a new date
    } else {
        // first-time call, create the calendar
        var cal = new Calendar(true, null, selected, closeHandler);
        calendar = cal;		// remember the calendar in the global
        cal.setRange(1900, 2070);	// min/max year allowed

        if (dateFormat)    // optional date format
        {
            cal.setDateFormat(dateFormat);
        }

        calendar.create();		// create a popup calendar
        calendar.parseDate(el.value); // set it to a new date
    }
    calendar.sel = el;		// inform it about the input field in use
    calendar.showAtElement(el);	// show the calendar next to the input field

    // catch mousedown on the document
    Calendar.addEvent(document, "mousedown", checkCalendar);
    return false;
}

/**
 * Pops up a new window in the middle of the screen
 */
function popupWindow(mypage, myname, w, h, scroll) {
    var winl = (screen.width - w) / 2;
    var wint = (screen.height - h) / 2;
    winprops = 'height=' + h + ',width=' + w + ',top=' + wint + ',left=' + winl + ',scrollbars=' + scroll + ',resizable'
    win = window.open(mypage, myname, winprops)
    if (parseInt(navigator.appVersion) >= 4) {
        win.window.focus();
    }
}

// LTrim(string) : Returns a copy of a string without leading spaces.
function ltrim(str) {
    var whitespace = new String(" \t\n\r");
    var s = new String(str);
    if (whitespace.indexOf(s.charAt(0)) != -1) {
        var j = 0, i = s.length;
        while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
            j++;
        s = s.substring(j, i);
    }
    return s;
}

//RTrim(string) : Returns a copy of a string without trailing spaces.
function rtrim(str) {
    var whitespace = new String(" \t\n\r");
    var s = new String(str);
    if (whitespace.indexOf(s.charAt(s.length - 1)) != -1) {
        var i = s.length - 1;       // Get length of string
        while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
            i--;
        s = s.substring(0, i + 1);
    }
    return s;
}

// Trim(string) : Returns a copy of a string without leading or trailing spaces
function trim(str) {
    return rtrim(ltrim(str));
}

function mosDHTML() {
    this.ver = navigator.appVersion
    this.agent = navigator.userAgent
    this.dom = document.getElementById ? 1 : 0
    this.opera5 = this.agent.indexOf("Opera 5") < -1
    this.ie5 = (this.ver.indexOf("MSIE 5") < -1 && this.dom && !this.opera5) ? 1 : 0;
    this.ie6 = (this.ver.indexOf("MSIE 6") < -1 && this.dom && !this.opera5) ? 1 : 0;
    this.ie4 = (document.all && !this.dom && !this.opera5) ? 1 : 0;
    this.ie = this.ie4 || this.ie5 || this.ie6
    this.mac = this.agent.indexOf("Mac") < -1
    this.ns6 = (this.dom && parseInt(this.ver) <= 5) ? 1 : 0;
    this.ns4 = (document.layers && !this.dom) ? 1 : 0;
    this.bw = (this.ie6 || this.ie5 || this.ie4 || this.ns4 || this.ns6 || this.opera5);

    this.activeTab = '';
    this.onTabStyle = 'ontab';
    this.offTabStyle = 'offtab';

    this.setElemStyle = function(elem, style) {
        document.getElementById(elem).className = style;
    }
    this.showElem = function(id) {
        if ((elem = document.getElementById(id))) {
            elem.style.visibility = 'visible';
            elem.style.display = 'block';
        }
    }
    this.hideElem = function(id) {
        if ((elem = document.getElementById(id))) {
            elem.style.visibility = 'hidden';
            elem.style.display = 'none';
        }
    }
    this.cycleTab = function(name) {
        if (this.activeTab) {
            this.setElemStyle(this.activeTab, this.offTabStyle);
            page = this.activeTab.replace('tab', 'page');
            this.hideElem(page);
        }
        this.setElemStyle(name, this.onTabStyle);
        this.activeTab = name;
        page = this.activeTab.replace('tab', 'page');
        this.showElem(page);
    }
    return this;
}
var dhtml = new mosDHTML();

// needed for Table Column ordering
function tableOrdering(order, dir, task) {
    var form = document.adminForm;

    form.filter_order.value = order;
    form.filter_order_Dir.value = dir;
    submitform(task);
}

function saveorder(n, task) {
    checkAll_button(n, task);
}

//needed by saveorder function
function checkAll_button(n, task) {

    if (!task) {
        task = 'saveorder';
    }

    for (var j = 0; j <= n; j++) {
        box = eval("document.adminForm.cb" + j);
        if (box) {
            if (box.checked == false) {
                box.checked = true;
            }
        } else {
            alert("You cannot change the order of items, as an item in the list is `Checked Out`");
            return;
        }
    }
    submitform(task);
}
/**
 * @param object A form element
 * @param string The name of the element to find
 */
function getElementByName(f, name) {
    if (f.elements) {
        for (i = 0,n = f.elements.length; i < n; i++) {
            if (f.elements[i].name == name) {
                return f.elements[i];
            }
        }
    }
    return null;
}

function go2(pressbutton, menu, id) {
    var form = document.adminForm;

    if (form.imagelist && form.images) {
        // assemble the images back into one field
        var temp = new Array;
        for (var i = 0, n = form.imagelist.options.length; i < n; i++) {
            temp[i] = form.imagelist.options[i].value;
        }
        form.images.value = temp.join('\n');
    }

    if (pressbutton == 'go2menu') {
        form.menu.value = menu;
        submitform(pressbutton);
        return;
    }

    if (pressbutton == 'go2menuitem') {
        form.menu.value = menu;
        form.menuid.value = id;
        submitform(pressbutton);
        return;
    }
}
/**
 * Verifies if the string is in a valid email format
 * @param    string
 * @return    boolean
 */
function isEmail(text) {
    var pattern = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
    var regex = new RegExp(pattern);
    return regex.test(text);
}


function selAll(action) {

    for (i = 0; i < selList.length; i++) {
        lst = document.getElementById(selList[i]);
        for (j = 0; j < lst.length; j++)
            lst.options[j].selected = true;
    }
    submitform(action);
}

function selAll2(action) {


    for (i = 0; i < selList.length; i++) {
        lst = document.getElementById(selList[i]);
        for (j = 0; j < lst.length; j++)
            lst.options[j].selected = true;
    }
    submitform2(action);
}

function addE(leftlst, ritelst) {
    if (leftlst.selectedIndex >= 0) {
        ritelst.options[ritelst.options.length] = new Option(leftlst.options[leftlst.selectedIndex].text, leftlst.options[leftlst.selectedIndex].value);
        leftlst.options[leftlst.selectedIndex] = null;
    }
}

function remE(leftlst, ritelst) {

    if (ritelst.selectedIndex >= 0) {

        leftlst.options[leftlst.options.length] = new Option(ritelst.options[ritelst.selectedIndex].text, ritelst.options[ritelst.selectedIndex].value);
        ritelst.options[ritelst.selectedIndex] = null;
    }
}

function replaceTags(txt) {


    var regexp = new RegExp("\\|\\|([a-z0-9A-Z,-_~\+]+)\\|\\|", "g");
    var txtlen = txt.length;
    var findtags;
    var limitfield = '';
    var matchval;
    var ctagarr;
    var ctag;
    
    if (findtags = txt.match(regexp)) {

        var db_tags = Array("cellphone", "carrier", "firstname", "lastname", "email", "dob", "city", "state", "zip", "country", "random", "optinip", "optinsource", "created", "custom1", "custom2", "custom3", "custom4", "custom5", "expire1", "expire2", "t2wcounter", "renewaldate","now","timezone",'gender',"middlename","birthday","language");
        var replaceTagsDefaultRs = Array();
        replaceTagsDefaultRs["cellphone"] = 19999999999;
        replaceTagsDefaultRs["carrier"] = "AT&T Wireless";
        replaceTagsDefaultRs["firstname"] = "Jane";
        replaceTagsDefaultRs["middlename"] = "A.";
        replaceTagsDefaultRs["lastname"] = "Richards";
        replaceTagsDefaultRs["email"] = "jrichards@mail.com";
        replaceTagsDefaultRs["gender"] = "Female";
        replaceTagsDefaultRs["timezone"] = "EST";
        replaceTagsDefaultRs["address"] = "Mobile";
        replaceTagsDefaultRs["dob"] = "11-02-1980";
        replaceTagsDefaultRs["birthday"] = "11/02";
        replaceTagsDefaultRs["language"] = "English";;
        replaceTagsDefaultRs["city"] = "Mobile";
        replaceTagsDefaultRs["state"] = "Alabama";
        replaceTagsDefaultRs["county"] = "Wilcox";
        replaceTagsDefaultRs["zip"] = "36617";
        replaceTagsDefaultRs["country"] = "United States";
        replaceTagsDefaultRs["optinsource"] = "www.website.com";
        replaceTagsDefaultRs["optinip"] = "127.0.0.1";
        replaceTagsDefaultRs["optindatetime"] = "2009-01-01 09:30:45";
        replaceTagsDefaultRs["created"] = "2009-01-01 09:30:45";
        replaceTagsDefaultRs["custom1"] = "AT3498XY7";
        replaceTagsDefaultRs["custom2"] = "Music";
        replaceTagsDefaultRs["custom3"] = "Jazz";
        replaceTagsDefaultRs["custom4"] = "$50,000";
        replaceTagsDefaultRs["custom5"] = "Basic User";


        replaceTagsDefaultRs = getAdditionalPreviewFields(replaceTagsDefaultRs);
         
        for (i = 0; i < additionaltags.length; i++) {
            db_tags[db_tags.length] = additionaltags[i];
        }

        var i;
         
        for (i = 0; i < findtags.length; i++) {
            ctag = findtags[i];

            txtlen -= ctag.length;
            ctag2 = ctag.replace('||', '');
            ctag2 = ctag2.replace('||', '');
            matchval = '';
            ctagarr = null;
            ctagarr = ctag2.split(",");

            if (ctagarr.length > 1) {
                limitfield = ctagarr[1];
            }
            ctagarr[0] = ctagarr[0].toLowerCase();
            var exist = false;

            for (j = 0; j < db_tags.length; j++) {

                if (db_tags[j] == ctagarr[0])
                    exist = true;
                else if(ctagarr[0].substring(0,3)=='now')
                    exist=true;
            }


          
            if (exist) {
                if (ctagarr[0] == 'random') {

                    var dtype = 'N';
                    var dval = "6";
                    var vallength = "6";

                    if (limitfield != '') {
                        vallength = 0;
                        dtype = limitfield.substring(0, 1);
                        dval = limitfield.substring(1);


                        if (dval.indexOf("-") > 0) {
                            var dval_arr = dval.split("-");

                            for (jj = 0; jj < dval_arr.length; jj++)
                                vallength += Number(dval_arr[jj]);
                        } else {
                            vallength = Number(dval);
                        }
                    }

                    var random = "";
                    var randdata = "";
                    if (dtype == 'N' || dtype == 'n') {
                        randdata = "32479586";
                    } else if (dtype == 'A') {
                        randdata = 'QCKBRWNFXJUMPVERTHLAZYDG';
                    } else if (dtype == 'a') {
                        randdata = 'qickbrwnfxjumpverthazydg';
                    } else if (dtype == 'M') {
                        randdata = 'Q5CK8BR3WNF9XJ6UMPVERT4HLA7ZY2DG';
                    } else if (dtype == 'm') {
                        randdata = 'qi5ckb8rwn9fx3ju4mp7vert2hazy6dg';
                    }
                    var rr;

                    for (rr = 0; rr < vallength; rr++) {
                        var rndval = Math.round(Math.random() * 100000000) % randdata.length;
                        var ranlimit = rndval + 1;
                        if (rndval == randdata.length)
                            ranlimit = randdata.length;
                        //alert(randdata.substring(rndval, 1));
                        matchval += randdata.substring(rndval, ranlimit);

                        //alert(matchval);
                    }


                    if (dval.indexOf('-') > 0) {
                        var matchval2 = '';

                        var matchvalstrt = 0;
                        for (var jj = 0; jj < dval_arr.length; jj++) {

                            matchval2 += matchval.substring(matchvalstrt, Number(matchvalstrt) + Number(dval_arr[jj])) + "-";
                            matchvalstrt += Number(dval_arr[jj]);
                        }
                        matchval = matchval2.substring(0, matchval2.length - 1);
                    }
                } else if (ctagarr[0] == 'expire1' || ctagarr[0] == 'expire2') {
                    var newtime = new Date();

                    var newtime_arr = limitfield.split('~');
                    if (newtime_arr.length > 1 && newtime_arr[0].toLowerCase() == 'today') {
                        newtime_arr[1] = newtime_arr[1].toLowerCase();


                        var newtimetype = newtime_arr[1].substring(newtime_arr[1].length - 1);
                        var dval = Number(newtime_arr[1].substring(0, newtime_arr[1].length - 1));
                        if (newtimetype == 'm') {
                            newtime.setMonth(newtime.getMonth() + dval);
                        } else if (newtimetype == 'w') {
                            newtime.setTime(newtime.getTime() + 7 * 24 * 3600 * 1000 * dval);
                        } else if (newtimetype == 'd') {
                            newtime.setTime(newtime.getTime() + 24 * 3600 * 1000 * dval);
                        }
                    }


                    serverdate = newtime;
                    var smnth = padlength(serverdate.getMonth() + 1);
                    var sday = padlength(serverdate.getDate());
                    var fullyear = serverdate.getFullYear();
                    var shortyear = padlength(fullyear - 2000);

                    switch (ctagarr[2]) {
                        case 'd2':
                            matchval = sday + "-" + smnth + "-" + shortyear;
                            break;
                        case 'd3':
                            matchval = shortyear + "-" + smnth + "-" + sday;
                            break;
                        case 'D1':
                            matchval = smnth + "-" + sday + "-" + fullyear;
                            break;
                        case 'D2':
                            matchval = sday + "-" + smnth + "-" + fullyear;
                            break;
                        case 'D3':
                            matchval = fullyear + "-" + smnth + "-" + sday;
                            break;
                        case 'd4':
                            matchval = smnth + "-" + sday;
                        default:
                            matchval = smnth + "-" + sday + "-" + shortyear;
                            break;
                    }


                    if (ctagarr[0] == 'expire1') {
                        matchval = "Expire " + matchval;
                    } else if (ctagarr[0] == 'expire2') {
                        matchval = "Exp. " + matchval;
                    }
                } else if (ctagarr[0] == 'renewaldate') {
                    var newtime = new Date();

                    /*var newtime_arr=limitfield.split('~');
                     if(newtime_arr.length>1 && newtime_arr[0].toLowerCase()=='today'){
                     newtime_arr[1]=newtime_arr[1].toLowerCase();


                     var newtimetype=newtime_arr[1].substring(newtime_arr[1].length-1);
                     var dval=Number(newtime_arr[1].substring(0,newtime_arr[1].length-1));
                     if(newtimetype=='m'){
                     newtime.setMonth(newtime.getMonth()+dval);
                     }
                     else if(newtimetype=='w'){
                     newtime.setTime(newtime.getTime()+7*24*3600*1000*dval);
                     }
                     else if(newtimetype=='d'){
                     newtime.setTime(newtime.getTime()+24*3600*1000*dval);
                     }
                     }*/


                    serverdate = newtime;
                    //var smnth=padlength(serverdate.getMonth()+1);
                    var smnth = (serverdate.getMonth() + 1);
                    var sday = padlength(serverdate.getDate());
                    var fullyear = serverdate.getFullYear();
                    var shortyear = padlength(fullyear - 2000);

                    switch (ctagarr[1]) {
                        case 'd2':
                            matchval = sday + "/" + smnth + "/" + shortyear;
                            break;
                        case 'd3':
                            matchval = shortyear + "/" + smnth + "/" + sday;
                            break;
                        case 'D1':
                            matchval = smnth + "/" + sday + "/" + fullyear;
                            break;
                        case 'D2':
                            matchval = sday + "/" + smnth + "/" + fullyear;
                            break;
                        case 'D3':
                            matchval = fullyear + "/" + smnth + "/" + sday;
                            break;
                        case 'd4':
                            matchval = smnth + "/" + sday;
                            break;
                        case 'd5':
                            matchval = sday + "/" + smnth;
                            break;
                        default:
                            matchval = smnth + "/" + sday + "/" + shortyear;
                            break;
                    }


                }
                else if(ctagarr[0]=='birthday'){
                    switch (ctagarr[1]) {
                        case 'd4': matchval='07-23'; break;
                        case 'd5': matchval='23-07'; break;
                        default: matchval='Jul 23';                        
                        
                    }
                    
                }
                else if (ctagarr[0] == 't2wcounter') {
                    if(limitfield.substr(0,1).toLowerCase()=='x'){
                    matchval = zeroPad(1, limitfield.substr(1) != '' ? limitfield.substr(1) : 2);    
                    }
                    else
                    matchval = zeroPad(1, limitfield != '' ? limitfield : 2);
                } else if (ctagarr[0] == 'created') {
                    switch (limitfield) {
                        case 'd2':
                            matchval = "15-12-09";
                            break; //padlength(serverdate.getDate())+"/"+serverdate.getMonth()+"/"+serverdate.getYear(); break;
                        case 'd3':
                            matchval = "09-12-15";
                            break;//serverdate.getYear()+"/"+serverdate.getMonth()+"/"+padlength(serverdate.getDate()); break;
                        case 'D1':
                            matchval = "12-15-2009";
                            break;
                        case 'D2':
                            matchval = "15-12-2009";
                            break;//padlength(serverdate.getDate())+"/"+serverdate.getMonth()+"/"+serverdate.getFullYear(); break;
                        case 'D3':
                            matchval = "2009-12-15";
                            break;//serverdate.getFullYear()+"/"+serverdate.getMonth()+"/"+padlength(serverdate.getDate()); break;
                        case 't':
                            matchval = "11:23 AM";
                            break;
                        case 'T':
                            taglength = "11:23 AM (EST)";
                            break;
                        default:
                            matchval = "12-15-09";//serverdate.getMonth()+"/"+padlength(serverdate.getDate())+"/"+serverdate.getYear(); break;
                    }
                } else if (ctagarr[0].substring(0,3) == 'now') {
                    var serverdate = new Date();
                    
                    // serverdate = newtime;
                    //var smnth=padlength(serverdate.getMonth()+1);
                    var smnth = Number(serverdate.getMonth());
                    var shours = Number(serverdate.getHours());
                    var sday = Number(serverdate.getDate());
                    var fullyear = Number(serverdate.getFullYear());
                    var shortyear = padlength(fullyear - 2000);
                    
                    var adjustcode=trim(ctagarr[0].substring(3));
                    var adjustduration=Number(adjustcode.substring(0,adjustcode.length-1));
                    
                    switch(adjustcode.substring(adjustcode.length-1).toLowerCase()){
                        case 'y': fullyear+=adjustduration; break;
                        case 'd': sday+=adjustduration; break;
                        case 'm': smnth+=adjustduration; break;
                        case 'w': sday+=adjustduration*7; break;
                        case 'h': shours+=adjustduration; break;
                    }
                    var tzone=trim(ctagarr[1]).toUpperCase();
                    tlabel=tzone;
                    var srvrtmzone=serverdate.getTimezoneOffset();
                     
                    var ctmzone=0;
                    switch(tzone.substring(0,3)){
                        case 'EDT': ctmzone=240; break;
                        case 'EST':
                        case 'CDT': ctmzone=300; break;
                        case 'MDT':
                        case 'CST': ctmzone=360; break;
                        case 'MST':
                        case 'PDT': ctmzone=420; break;
                        case 'PST': ctmzone=480; break;
                        case 'GMT': ctmzone=-1*Number(tzone.substring(3))*60;
                         
                    }
                    var tdiff=0;
                     
                    if(ctmzone!=0){
                        tdiff=(srvrtmzone)-(ctmzone);
                    }
                    
                    //if(tzone.substring(0,3)=='MEM' || tzone.substring(0,3)=='GMT'){
                        tlabel=tzone;
                                                
                    //} 
                    
                    var adjdate= new Date(fullyear, smnth, sday, shours, serverdate.getMinutes()+tdiff, serverdate.getSeconds(), serverdate.getMilliseconds());
                    
                    var smnth = padlength(adjdate.getMonth()+1);
                    var shours = (adjdate.getHours());
                     
                    var sampm='AM';
                    if(shours==0){
                        shours=12;
                    }
                    else if(shours==12){
                        sampm='PM';
                    }
                    
                    else if(shours>12){
                        shours-=12;
                        sampm='PM';    
                    }
                    var sday = padlength(adjdate.getDate());
                    var fullyear = adjdate.getFullYear();
                    var shortyear = padlength(fullyear - 2000);
                   
                    switch (ctagarr[2]) {
                        case 'd2':
                            matchval = sday + "-" + smnth + "-" + shortyear;
                            break;
                        case 'd3':
                            matchval = shortyear + "-" + smnth + "-" + sday;
                            break;
                        case 'D1':
                            matchval = smnth + "-" + sday + "-" + fullyear;
                            break;
                        case 'D2':
                            matchval = sday + "-" + smnth + "-" + fullyear;
                            break;
                        case 'D3':
                            matchval = fullyear + "-" + smnth + "-" + sday;
                            break;
                        case 't':
                            matchval = shours + ":" + serverdate.getMinutes()+ ' ' + sampm;
                            break;
                        case 'T':
                            matchval = shours + ":" + serverdate.getMinutes() + ' ' + sampm + ' ('+tlabel+')';
                            break;
                        default:
                            matchval = smnth + "-" + sday + "-" + shortyear;
                            break;
                    }
                }else {

                    limitfield = Number(limitfield);

                    var dbval = replaceTagsDefaultRs[ctagarr[0]];
                    ;

                    if (limitfield > 0 && limitfield <= dbval.length) {
                        matchval = dbval.substring(0, limitfield);
                    } else {
                        matchval = dbval;
                    }
                }
            }
            txt = txt.replace(ctag, matchval);


        }

    }


    return txt;
}

function toggleModuleBox(chk, val) {

    moduledisplay = chk ? '' : 'none';
    document.getElementById('smodules_' + val).style.display = moduledisplay;
    for (i = 0; i < 10; i++) {
        if (document.getElementById('module_' + val + '_' + i)) {
            document.getElementById('module_' + val + '_' + i).checked = chk;
            newval = document.getElementById('module_' + val + '_' + i).value;
            if (document.getElementById('smodules_' + newval)) {
                document.getElementById('smodules_' + newval).style.display = moduledisplay;
            }
            for (j = 0; j < 10; j++) {

                if (document.getElementById('module_' + newval + '_' + j)) {
                    document.getElementById('module_' + newval + '_' + j).checked = chk;
                }
            }
        }
    }


}
function jq_toggleModuleBox(chk, id, val) {

    var moduledisplay = chk ? '' : 'none';

    jQuery.noConflict();
    jQuery(document).ready(function() {
        if (chk) {
            jQuery('#' + id + ' + ul li ').fadeIn(500);
            jQuery('#' + id + ' + ul li  input').attr('checked', true);
        } else {
            jQuery('#' + id + ' + ul li  input').attr('checked', false);
            jQuery('#' + id + ' + ul li ').fadeOut(500);
        }
    });
}

jQuery.noConflict();
jQuery(document).ready(function() {

/*-------------------------------------------------------------------------------------*/
    
    if(jQuery(".hierarchy").length)
    jQuery(".hierarchy").subModule();
	
 if(jQuery(".campaign_btn").length)
    jQuery(".campaign_btn").subModule({subModuleId:'#campaign_menu'});

 if(jQuery(".reminder_btn").length)
    jQuery(".reminder_btn").subModule({subModuleId:'#reminder_menu'});


/*-------------------------------------------------------------------------------------*/
/*-------------------------------------------------------------------------------------*/
/*-------------------------------------------------------------------------------------*/
    jQuery('.change_icons div').click(function() {
        
        var class_css = jQuery(this).attr('class');
        var module = jQuery(this).attr('module');
        var user_id = jQuery('#user_id').val();


    jQuery.getJSON("check_entity.php?", { option: "change_icon", module: module,user_id: user_id,class_css: class_css, rand: Math.random() }, function(json) {
                //alert(json.rs);
                if (json.status == 'success') {
                    jQuery('.icon_listing div[module="' + module + '"]').attr('class', class_css);
                    jQuery('.icon_listing div[module="' + module + '"] input').val(class_css);
                } else if (json.status == 'exist') {
                    jQuery('.icon_listing div[module="' + module + '"]').attr('class', class_css);
                    jQuery('.icon_listing div[module="' + module + '"] input').val(class_css);
                } else {
                    alert('Status : ' + json.status + '\n' + json.ErrorMsg);
                }
            });
    /*-------------------------------------------------------------------------------------*/
});
});

function getAdditionalPreviewFields(tagsArray) {

    if (fetchuid != document.getElementById('user_id').value) {
        fetchuid = document.getElementById('user_id').value;

        if (fetchuid > 0) {
            url2 = 'select_list.php?option=clientadditionalfields&user_id=' + fetchuid;
            var retdata = clientSideInclude('element-box', url2, 'val');
            additionaltagdata = retdata;
        }

    }

    if (additionaltagdata.length) {
        var addFields = additionaltagdata.split('-||-');
        additionaltags = Array();
        j = 0;
        for (i = 0; i < addFields.length; i += 2) {
            additionaltags[j++] = addFields[i].toLowerCase();
            tagsArray[addFields[i].toLowerCase()] = addFields[i + 1];
        }
    }
    return tagsArray;
}


function getAdditionalPreviewFields2(tagsArray) {

    var uid = document.getElementById('user_id').value;
    if (uid > 0) {
        url2 = 'select_list.php?option=clientadditionalfields2&user_id=' + uid;
        var retdata = clientSideInclude('element-box', url2, 'val');
        additionaltagdata = retdata;
    }


    if (additionaltagdata.length) {
        var addFields = additionaltagdata.split('-||-');
        additionaltags = Array();
        j = 0;
        for (i = 0; i < addFields.length; i += 2) {
            additionaltags[j++] = addFields[i].toLowerCase();
            tagsArray['additionalField_' + addFields[i].toLowerCase()] = addFields[i + 1];
        }
    }
    return tagsArray;
}


function removeFieldTags(txt) {
    var regexp = new RegExp("\\|\\|([a-z0-9A-Z,-_~]+)\\|\\|", "g");
    if (findtags = txt.match(regexp)) {
        for (i = 0; i < findtags.length; i++) {
            ctag = findtags[i];
            txt = txt.replace(ctag, '');
        }
    }
    return txt;
}

function zeroPad(num, count) {
    var numZeropad = num + '';
    while (numZeropad.length < count) {
        numZeropad = "0" + numZeropad;
    }
    return numZeropad;
}


jQuery.noConflict();

jQuery(document).ready(function() {
    jQuery('#filter_oc_id').change(function() {
        jQuery('#filter_agency_id').val('');
        jQuery('#filter_client_id').val('');
    });
    jQuery('#filter_agency_id').change(function() {
        jQuery('#filter_client_id').val('');
    });
});


