﻿var iemmysSite = {

    init: function () {

        if (!($('body').hasClass('homepage'))) {
            this.positionElements();
        }
        this.squeezeLeftNav();

        $('textarea[maxlength]').textAreaMaxLength();

    },

    positionElements: function () {
        var mainOuter = $('#mainOuter');
        var botNav = $('#botNav');
        var contentDiv = $('#contentOuter');
        var mainOuterHeight = mainOuter.height();
        var rightZone = $('.siteRightZone:first');
        var rightZoneOffset = rightZone.offset();
        var isWideZones = $('#aspnetForm').hasClass('wideZonesForm');

        var intervalCount = 0;
        var positionTimer = setInterval(function () {

            mainOuterHeight = mainOuter.height();

            var botNavOffset = botNav.offset();
            botNav.css({ zIndex: 1, top: botNavOffset.top, left: botNavOffset.left });

            var contentOffset = contentDiv.offset();
            contentDiv.css({ zIndex: 2, top: contentOffset.top, left: contentOffset.left });

            intervalCount++;

            if (intervalCount >= 4) {
                clearInterval(positionTimer);
                mainOuter.css('height', mainOuterHeight + 'px');
                //$('.leftNavBG').height(mainOuterHeight + 'px');

                $('#leftZoneBG').css({ display: 'block', top: contentOffset.top, left: contentOffset.left });
                $('#rightZoneBG').css({ display: 'block', height: (contentDiv.height() - parseInt(rightZone.css('padding-top'))), top: rightZoneOffset.top });

                $('table.siteLeftZone').css('background-color', 'transparent');
                botNav.css({ position: 'absolute' });
                contentDiv.css({ position: 'absolute' });

                if (isWideZones) {
                    $('table.siteZonesTbl').css('table-layout', 'auto');
                    $('td.siteLeftZone').hide();
                    $('td.siteZoneMid').css('padding-left', 0);
                    $('#rightZoneBG').width($('table.siteRightZone:first').outerWidth());
                } else {
                    $('#leftZoneBG').css({ height: contentDiv.height() });
                    $('#rightZoneBG').css({ left: rightZoneOffset.left });
                }
            }
        }, 500);

        if (screen) {
            if (screen.width < mainOuter.width())
                $('body').css('overflow', 'auto');
        }
    },

    squeezeLeftNav: function () {
        var ul = $('.leftNav ul:first');
        var li = $('.leftNav li');
        if (li.length > 0) {
            var paddingTop = li.css("padding-top").replace("px", "");
            var fontSize = li.css("font-size").replace("px", "")
            var minPadding = 8;
            var minFont = 10;
            var maxHeight = ul.height();
            ul.css('height', 'auto');
            var ulHeight = ul.height();

            while (ulHeight > maxHeight && paddingTop >= minPadding+1) {
                //console.log('ulHeight=' + ulHeight + ' maxHeight=' + maxHeight + ' paddingTop=' + paddingTop + ' minPadding=' + minPadding);
                paddingTop--;
                li.css("padding-top", paddingTop + "px");
                ulHeight = ul.height();
                if (ulHeight <= maxHeight)
                    break;
                else {
                    //                fontSize = (fontSize - 1) > minFont ? (fontSize - 1) : minFont;
                    //                li.css("font-size", fontSize + "px");
                    //                ulHeight = ul.height();
                }

            }
            //ul.css('height', maxHeight + "px");
        }
    }
};

$(document).ready(function () {
    iemmysSite.init();
});

$.fn.textAreaMaxLength = function () {
    /// <summary>Adds support for the maxlength attribute to textarea</summary>
    return this.each(function () {
        if (this.tagName.toLowerCase() == 'textarea') {
            var max = parseInt($(this).attr('maxlength'));

            //Add the key press event
            this.onkeypress = function (e) {
                //Get the event object (for IE)
                var ob = e || event;
                //Get the code of key pressed
                var keyCode = ob.keyCode;
                //Check if it has a selected text
                var hasSelection = document.selection ? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;
                //return false if can't write more
                return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);
            };

            //Add the key up event
            this.onkeyup = function () {
                //If the keypress fail and allow write more text that required, this event will remove it
                if (this.value.length > max) {
                    this.value = this.value.substring(0, max);
                }
            };
        }
    });
};


function returnObjById(id) {
    var returnVar;
    if (document.getElementById) 
        returnVar = document.getElementById(id); 
    else if (document.all) 
        returnVar = document.all[id]; 
    else if (document.layers) 
        returnVar = document.layers[id]; 
    return returnVar; 
}
 
function WriteInnerHTML(divId, strHtml) {
    if (document.getElementById) {
        document.getElementById(divId).innerHTML = strHtml;
	} else if (document.all) {
		document.all[divId].innerHTML = strHtml;
    } else {
        with (document.layers[divId].document) {
            open();
            write(strHtml);
            close();
        }
    }
}

// cross-browser function to get an object's style object given its id
function getStyleObject(objectId) {
    if (document.getElementById && document.getElementById(objectId)) { // W3C DOM	    
	    return document.getElementById(objectId).style;
    } else if (document.all && document.all(objectId)) { // MSIE 4 DOM	    
	    return document.all(objectId).style;
    } else if (document.layers && document.layers[objectId]) { // NN 4 DOM.. note: this won't find nested layers	    
	    return document.layers[objectId];
    } else {
	    return false;
    }
}

function toggleShowHide(obj) {
    var currentDisplay = (getStyleObject(obj).display == 'none') ? 'block' : 'none';
    getStyleObject(obj).display = currentDisplay;
}
function show(obj) {
    getStyleObject(obj).display = 'block';
}
function hide(obj) {
    getStyleObject(obj).display = 'none';
}

//Cookies
function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) 
                c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        } 
    }
    return "";
}

function Set_Cookie(name, value, expires, path, domain, secure) {
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime(today.getTime());

    /*
    if the expires variable is set, make the correct
    expires time, the current script below will set
    it for x number of days, to make it for hours,
    delete * 24, for minutes, delete * 60 * 24
    */
    if (expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date(today.getTime() + (expires));

    document.cookie = name + "=" + escape(value) + ((expires) ? ";expires=" + expires_date.toGMTString() : "") + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ((secure) ? ";secure" : "");
}

// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie(check_name) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split(';');
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f

    for (i = 0; i < a_all_cookies.length; i++) {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split('=');


        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
        if (cookie_name == check_name) {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if (a_temp_cookie.length > 1) {
                cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if (!b_cookie_found) {
        return null;
    }
}

// this deletes the cookie when called
function Delete_Cookie(name, path, domain) {
    if (Get_Cookie(name)) 
        document.cookie = name + "=" + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
	

function WebPartMgrBar_OnLoad() {
    //alert(wpmId);
    var wpm = returnObjById(wpmId);
    var obj = returnObjById('wpmToggler');
    var togglestate = Get_Cookie('togglestate');
    if (togglestate == null || togglestate == '' || togglestate == 'maximized') {
        wpm.style.height = '420px';
        obj.innerHTML = 'Minimize';
        Set_Cookie('togglestate', 'maximized', 365, '/', '', '');
    } else {
        wpm.style.height = '15px';
        obj.innerHTML = 'Maximize';
        Set_Cookie('togglestate', 'minimized', 365, '/', '', '');
    }
}

function WebPartMgrBar_Toggle(obj) {
    //alert(wpmId);
    var wpm = returnObjById(wpmId);
    if (wpm.style.height == '15px') {
        wpm.style.height = '420px';
        obj.innerHTML = 'Minimize';
        Set_Cookie('togglestate', 'maximized', 365, '/', '', '');
    } else {
        wpm.style.height = '15px';
        obj.innerHTML = 'Maximize';
        Set_Cookie('togglestate', 'minimized', 365, '/', '', '');
    }
}


//Side Nav
function rollOn(imgName) {
	if (document.images) {
    	document[imgName].src = eval(imgName + "_on.src");
	}
}
function rollOff(imgName) {
	if (document.images) {
		document[imgName].src = eval(imgName + "_off.src");
	}
}


function findObj(n, d) {
	var p,i,x;  if(!d) d=opener.document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
	d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
	if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=findObj(n,d.layers[i].document);
	if(!x && d.getElementById) x=d.getElementById(n); return x;
}

// Entry Form Rows
var currRow;
var oldRowClass;
function rowOn(obj) {
    do {
        obj = obj.parentNode;
        //alert(obj.tagName + ' ' + obj.className);
    } while (!(obj.tagName == 'TR' && obj.className.indexOf('entryformrow') != -1));
    //obj = obj.parentNode;
    currRow = obj;
    oldRowClass = obj.className;
    obj.className = "entryformrowOn";
}
function rowOff(obj) {
    //do { obj = obj.parentNode; } while (!(obj.tagName == 'tr' && obj.className.indexOf('entryformrowOn') != -1));
    currRow.className = oldRowClass;
}

function formatCategories(id) {
    var radioTbl = $('#' + id);
    if (radioTbl.length > 0) {
        
        $('tr', radioTbl).addClass('entryformcatrow');
        var rows = $('tr.entryformcatrow', radioTbl);

        var cathdr;
        $('.category_hdr', radioTbl).each(function () {
            var $item = $(this);
            var itemtext = $item.text();
            if (cathdr != itemtext) {
                var itemhtml = '<tr><td class="goldHeader">' + itemtext + '</td></tr>';
                $item.parents('tr:first').before(itemhtml);
            }
            cathdr = itemtext;
        });

        rows.each(function () {
            var row = $(this);
            var radio = $("input", row);

            row.css({ verticalAlign: 'top' }).hover(function () {
                $(this).addClass('entryformcatrowOn');
            }, function () {
                if (!radio.attr('checked'))
                    $(this).removeClass('entryformcatrowOn');
            });

            radio.click(function () {
                rows.removeClass('entryformcatrowOn');
                $(this).parents('tr:first').addClass('entryformcatrowOn');
            });
        });

        radioTbl.show();
        iemmysSite.positionElements();
    }
}

function showButtons(id) {
    var btns = returnObjById(id);
    if ((btns != undefined) && (btns != null)) {
        btns.style.display = 'block';
    }
}


function GetMaxWords(targetField) {
    return targetField.exMaxWords;
}

function LimitWords(targetField, counterElement, sourceEvent) {
    var isPermittedKeystroke;
    var enteredKeystroke;
    var maximumWordCount;
    var currentWordCount;
    var inputAllowed = true;
    var selectionWordCount = parseInt(CountWordsInSelection(targetField));

    if (GetMaxWords(targetField) != null) {
        // Get the current and maximum field length
        maximumWordCount = parseInt(GetMaxWords(targetField));
        currentWordCount = parseInt(CountWordsInString(targetField.value));

        // Allow non-printing, arrow and delete keys
        enteredKeystroke = window.event ? sourceEvent.keyCode : sourceEvent.which;
        isPermittedKeystroke = ((enteredKeystroke < 32)                                // Non printing
                 || (enteredKeystroke >= 33 && enteredKeystroke <= 40)    // Page Up, Down, Home, End, Arrow
                 || (enteredKeystroke == 46))                            // Delete

        // Decide whether the keystroke is allowed to proceed
        if (!isPermittedKeystroke) {
            if ((currentWordCount - selectionWordCount) >= maximumWordCount) {
                inputAllowed = false;
            }
        }

        // Force a trim of the textarea contents if necessary
        if (currentWordCount > maximumWordCount) {
            //targetField.value = targetField.value.substring(0, maximumFieldLength)
        }
    }

    var remainingWordCount = parseInt(maximumWordCount - currentWordCount);
    WriteInnerHTML(counterElement, remainingWordCount + ' Words Remaining');

    sourceEvent.returnValue = inputAllowed;
    return (inputAllowed);
}

function LimitPasteWords(targetField, counterElement, sourceEvent) {
    var clipboardText = '';
    var resultantWordCount;
    var maximumWordCount;
    var currentWordCount;
    var pasteAllowed = true;
    var selectionWordCount = parseInt(CountWordsInSelection(targetField));

    if (GetMaxWords(targetField) != null) {
        // Get the current and maximum field length
        maximumWordCount = parseInt(GetMaxWords(targetField));
        currentWordCount = parseInt(CountWordsInString(targetField.value));

        if (window.clipboardData)
            clipboardText = window.clipboardData.getData("Text");
        resultantWordCount = currentWordCount + CountWordsInString(clipboardText) - selectionWordCount;
        if (resultantWordCount > maximumWordCount) {
            pasteAllowed = false;
        }
    }
    
    var remainingWordCount = parseInt(maximumWordCount - currentWordCount);
    WriteInnerHTML(counterElement, remainingWordCount + ' Words Remaining');

    sourceEvent.returnValue = pasteAllowed;
    return (pasteAllowed);
}


function CountWordsInSelection(targetField) {
    if (targetField.selectionStart == undefined) {
        return CountWordsInString(document.selection.createRange().text);
    }
    else {
        return CountWordsInString(targetField.value.substring(targetField.selectionStart, targetField.selectionEnd));
    }
}

function CountWords(txtfield, divId, wordMax) {
    var char_count = txtfield.value.length;
    var fullStr = txtfield.value + " ";
    var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
    var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
    var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
    var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
    var splitString = cleanedStr.split(" ");
    var word_count = splitString.length - 1;
    if (fullStr.length < 2) {
        word_count = 0;
    }
    word_remain = wordMax - word_count;
    WriteInnerHTML(divId, word_remain);
    return word_count;
}
function CountWordsInString(str) {
    var char_count = str.length;
    var fullStr = str + " ";
    var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
    var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
    var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
    var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
    var splitString = cleanedStr.split(" ");
    var word_count = splitString.length - 1;
    if (fullStr.length < 2) {
        word_count = 0;
    }
    return word_count;
}

function showButtons() {
    var btns = returnObjById('actionbuttons');
    if ((btns != undefined) && (btns != null)) {
        btns.style.display = 'block';
    }
}


//######## Open Centered Window #############
function OpenCenteredWindow(url, width, height, windowname)
{
	var x, y = 0;
	if (screen) {
		x = (screen.availWidth - width) / 2;
		y = (screen.availHeight - height) / 2;
	}   
	var options = "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,width=" + width + ",height=" + height + ",screenX=" + x + ",screenY=" + y + ",left=" + x + ",top=" + y;
	if (windowname == null) {
	    windowname = "new";
	}
	msgWindow=window.open(url,windowname,options);		
}

function OpenCenteredWindowOptions(url, width, height, scrollbars, resizable, windowname)
{
	var x, y = 0;
	if (screen) {
		x = (screen.availWidth - width) / 2;
		y = (screen.availHeight - height) / 2;
	}   
	var options = "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=" + scrollbars + ",resizable=" + resizable + ",width=" + width + ",height=" + height + ",screenX=" + x + ",screenY=" + y + ",left=" + x + ",top=" + y;
	if (windowname == null) {
	    windowname = "new";
	}
	msgWindow=window.open(url,windowname,options);		
}


