﻿function findPos(Obj)
{
	var cureft = curtop = 0;
	if (Obj.offsetParent)
	{
		curleft = Obj.offsetLeft
		curtop = Obj.offsetTop
		
		while (Obj = Obj.offsetParent)
		{
			curleft += Obj.offsetLeft
			curtop += Obj.offsetTop
		}
	}
	return [curleft,curtop];
}


var _modalSetup = false;
function setupModalWindow()
{
    if (_modalSetup == false)
    {
        var s = "";
        s = s + "<div id=\"modalWindow\" class=\"dialog_frame\"><div id=\"modalWindowInner\" class=\"dialog_frameinner\">";
        s = s + "<div class=\"dialog_header\"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"width: 100%\"><tr><td><span id=\"modalWindowTitle\" class=\"dialog_headertitle\"></span></td><td align=\"right\" nowrap=\"nowrap\"><img src=\"images/modalclose_off.png\" onmouseover=\"this.src='images/modalclose.png';\" onmouseout=\"this.src='images/modalclose_off.png';\" style=\"height: 19px; width: 19px; padding: 4px 0px 4px 4px;\" onclick=\"hideModalWindow();\"/></td></tr></table></div>";
        s = s + "<div class=\"dialog_inner\" style=\"position: relative; padding: 2px 2px 2px 2px; margin: 0px 6px 0px 6px;\">";
        s = s + "<div id=\"modalWindowLoading\" style=\"position: relative; display: none; width: 98%; text-align: center; -moz-user-select: none; -khtml-user-select: none;\"><img style=\"padding-top: 120px;\" src=\"images/loading_sm.gif\" /><br /><span id=\"modalloadtext\" style=\"-moz-user-select: none; -khtml-user-select: none;\">Loading</span></div>";
        s = s + "<div id=\"modalWindowContent\"></div>";
        s = s + "</div></div></div>";
        s = s + "<div id=\"modalBackground\" style=\"position: fixed; left: 0; top: 0; width: 100%; height: 100%; z-index: 998;display: none; background-color: #000; opacity: 0.20; filter:alpha(opacity=20); -moz-opacity: 0.20;\"></div>";
        
        var div = document.createElement("div");
        div.innerHTML = s;
        document.body.appendChild(div);
        
        _modalSetup = true;
    }
}


function showModalWindow(Title, Content, Height, Width)
{
    setupModalWindow();
    
    document.getElementById('modalWindowTitle').innerHTML = Title;
    document.getElementById('modalWindowContent').innerHTML = "Loading...";
    document.getElementById('modalWindowInner').style.height = Height + 5 + 'px';
    document.getElementById('modalWindowInner').style.width = Width + 'px';
    document.getElementById('modalWindow').style.display = 'block';
    $('#modalBackground').fadeIn('fast');
    
    // call once to center everything
	modalWindowOnWindowResize();
    
    if (window.attachEvent)
		window.attachEvent('onresize', modalWindowOnWindowResize);
	else if (window.addEventListener)
		window.addEventListener('resize', modalWindowOnWindowResize, false);
	else
		window.onresize = modalWindowOnWindowResize;
	
	if (document.all)
		document.documentElement.onscroll = modalWindowOnWindowResize;

		
	//Apppend content
	document.getElementById('modalWindowContent').style.display='none';
	document.getElementById('modalWindowContent').innerHTML = Content;
	
	//See if the content is an iframe
	if (Content.indexOf("iframe") > 0)
	{
	    document.getElementById('modalWindowLoading').style.height = Height - 40 + 'px';
	    document.getElementById('modalWindowLoading').style.display='block';
	    $("iframe").bind("load", function(e){
            document.getElementById('modalWindowLoading').style.display='none';
            document.getElementById('modalWindowContent').style.display='block';
        });
	}
	else
	{
	    document.getElementById('modalWindowContent').style.display='block';
	}
}

function showModalWindowiFrame(Title, URL, Height, Width)
{
    showModalWindow(Title, '<div style="padding: 0px;"><iframe src="' + URL + '" width="100%" height="' + (Height - 40) + '" frameborder="0" align="middle" scrolling="auto">loading...</iframe></div>', Height, Width);
}

function showModalWindowAppendDiv(Title, DivID, moveToaspnetForm)
{
    showModalWindow(Title, '<div id="modalWindowAppendTo" style="padding: 0px;"></div>', $('#' + DivID).height() + 60, 500);
    $('#modalWindowAppendTo').append($('#' + DivID));
    
    if (moveToaspnetForm == true) { $('#aspnetForm').append($('#modalWindow')); }
}


function modalWindowOnWindowResize()
{
	var left = window.XMLHttpRequest == null ? document.documentElement.scrollLeft : 0;
	var top = window.XMLHttpRequest == null ? document.documentElement.scrollTop : 0;
	var div = document.getElementById('modalWindow');
	
	left = Math.max((left + (getWindowWidth() - div.offsetWidth) / 2), 0);
	if (left < 6) { left = 6; }
	div.style.left = left + 'px';
	
	top = (Math.max((top + (getWindowHeight() - div.offsetHeight) / 2), 0) - 40);
	if (top < 6) { top = 6; }
	div.style.top = top + 'px';
}


function hideModalWindow()
{
    
    if (document.getElementById('modalBackground'))
    {
        $('#modalBackground').fadeOut('fast');
    }
    
    if (document.getElementById('modalWindow'))
    {
        document.getElementById('modalWindow').style.display = 'none';
    	
	    if (window.detachEvent)
		    window.detachEvent('onresize', modalWindowOnWindowResize);
	    else if (window.removeEventListener)
		    window.removeEventListener('resize', modalWindowOnWindowResize, false);
	    else
		    window.onresize = null;
    }
}



function getWindowWidth()
{
	var width =
		document.documentElement && document.documentElement.clientWidth ||
		document.body && document.body.clientWidth ||
		document.body && document.body.parentNode && document.body.parentNode.clientWidth ||
		0;
		
	return width;
}

function getWindowHeight()
{
    var height =
		document.documentElement && document.documentElement.clientHeight ||
		document.body && document.body.clientHeight ||
  		document.body && document.body.parentNode && document.body.parentNode.clientHeight ||
  		0;
  		
  	return height;
}






function setStatusMessage(message)
{
    $(document).ready(function() {
    
        document.getElementById('statusMessage').innerHTML=message;
      
        $('#statusMessage').slideDown('slow');
        
        setTimeout(function ()
        { 
            $('#statusMessage').slideUp('fast');
        }, 8000);
       
    });
    
}



function showMediaWindow(mediaid, height, width)
{
    showModalWindowiFrame('', 'dialog_media.aspx?mediaid=' + mediaid, Math.min(Math.max(500, height + 130), 800), Math.min(Math.max(600, width + 40), 1000));
}

function showTestApplicationV1Modal(appid)
{
    showModalWindowiFrame('Test Your App on an iPhone', 'dialog_downloadviewerv1.aspx?appid=' + appid, 500, 600);
}


function showTestApplicationVectorModal(appcode)
{
    showModalWindowiFrame('Test your app in real time on your device with VIZ.', 'dialog_installvizvector.aspx?appcode=' + appcode, 560, 620);
}

function showTemplateAppVectorModal(title, appcode)
{
    showModalWindowiFrame(title, 'dialog_downloadviewertemplatevector.aspx?appcode=' + appcode, 560, 620);
}

function showDesignBuildModal()
{
    showModalWindowiFrame('Red Foundry Design & Build Packages', 'http://redfoundry.wufoo.com/forms/design-build-packages/', 520, 660);
}


function showURLModal(url, height, width)
{
    if (url.length < 10)
    {
        alert('The URL you have entered is not valid. Please include a full URL starting with http://.');
    }
    else
    {
        showModalWindow(url, '<div style="padding: 0px;"><iframe src="' + url + '" width="100%" height="' + (height - 40) + '' + '" frameborder="0" align="middle" scrolling="auto">loading...</iframe></div>', height, width);
    }
}

function showMovieWindow(title, movieurl, height, width)
{
    showModalWindow(title, '<object width="' + width + '" height="' + height + '" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab"><param name="src" value="' + movieurl + '"><param name="autoplay" value="true"><param name="controller" value="false"><embed src="' + movieurl + '" width="' + width + '" height="' + height + '" autoplay="true" controller="false" pluginspage="http://www.apple.com/quicktime/download/"></embed></object>', height + 40, width + 40);
}



function setLatitudeLongitudeModal(latlngid)
{
    var latlng = $('#' + latlngid).val();
    showModalWindowiFrame('Select a Map Point', 'dialog_latitudelongitude.aspx?latlng=' + latlng + '&latlngid=' + latlngid, 500, 540);
}


function showLatitudeLongitudeModal(title, lat, lng)
{
    var latlng = lat + ":" + lng;
    showModalWindowiFrame(title, 'dialog_showmap.aspx?lat=' + lat + '&lng=' + lng, 500, 540);
}


function fireSettingShowIf(componentid, val)
{
    $(".parentcomponentsettingid_" + componentid).each(function (i) 
    {
        if ($(this).attr("showifval") == val) { $(this).slideDown('fast'); }
        else { $(this).slideUp('fast'); }
    });
}

var previousPoint = null;
function enableGraphTooltip(graphdiv)
{
    $("#" + graphdiv).bind("plothover", function (event, pos, item) 
    {
        $("#x").text(pos.x.toFixed(2));
        $("#y").text(pos.y.toFixed(2));
 
        if (item) 
        {
            if (previousPoint != item.datapoint) 
            {
                previousPoint = item.datapoint;
                $("#graphtooltip").remove();
                var x = item.datapoint[0].toFixed(2), y = item.datapoint[1].toFixed(0);
                showGraphTooltip(item.pageX, item.pageY, y);
            }
        }
        else 
        {
            $("#graphtooltip").remove(); previousPoint = null;            
        }
    });
}


function enableGraphTooltipDate(graphdiv, prepend)
{
    $("#" + graphdiv).bind("plothover", function (event, pos, item) 
    {
        $("#x").text(pos.x.toFixed(2));
        $("#y").text(pos.y.toFixed(2));
 
        if (item) 
        {
            if (previousPoint != item.datapoint) 
            {
                previousPoint = item.datapoint;
                $("#graphtooltip").remove();
                var y = item.datapoint[1].toFixed(0);
                var d = new Date(item.datapoint[0]); d.setDate(d.getDate() + 1);
                showGraphTooltip(item.pageX, item.pageY, '<div class="textm1" style="font-weight: normal;">' + dateFormat(d, 'dddd, mmmm d') + '</div><div>' + prepend + ': ' + item.datapoint[1].toFixed(0) + '</div>');
            }
        }
        else 
        {
            $("#graphtooltip").remove(); previousPoint = null;            
        }
    });
}


function enableGraphTooltipCurrency(graphdiv, prepend)
{
    $("#" + graphdiv).bind("plothover", function (event, pos, item) 
    {
        $("#x").text(pos.x.toFixed(2));
        $("#y").text(pos.y.toFixed(2));
 
        if (item) 
        {
            if (previousPoint != item.datapoint) 
            {
                previousPoint = item.datapoint;
                $("#graphtooltip").remove();
                var y = item.datapoint[1].toFixed(2);
                var d = new Date(item.datapoint[0]); d.setDate(d.getDate() + 1);
                var mn=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
                showGraphTooltip(item.pageX, item.pageY, '<div class="textm1" style="font-weight: normal;">' + mn[d.getMonth()] + ' ' + d.getDate() + '</div><div>' + prepend + ': ' + item.datapoint[1].toFixed(0) + '</div>');
            }
        }
        else 
        {
            $("#graphtooltip").remove(); previousPoint = null;            
        }
    });
}


function enableGraphRankTooltip(graphdiv)
{
    $("#" + graphdiv).bind("plothover", function (event, pos, item) 
    {
        $("#x").text(pos.x.toFixed(2));
        $("#y").text(pos.y.toFixed(2));
 
        if (item) 
        {
            if (previousPoint != item.datapoint) 
            {
                previousPoint = item.datapoint;
                $("#graphtooltip").remove();
                var y = "#" + (300 - item.datapoint[1].toFixed(0));
                var d = new Date(item.datapoint[0]);
                var mn=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
                if (y == "#301") { y = "Below #300"; }
                showGraphTooltip(item.pageX, item.pageY, '<div class="textm1" style="font-weight: normal;">' + mn[d.getMonth()] + ' ' + d.getDate() + '</div><div>Rank: ' + y + '</div>');
            }
        }
        else 
        {
            $("#graphtooltip").remove(); previousPoint = null;            
        }
    });
}


function showGraphTooltip(x, y, contents)
{
    $('<div id="graphtooltip">' + contents + '</div>').css( {position: 'absolute',display: 'none',top: y - 28,left: x + 10,border: '1px solid #999999',padding: '6px','background-color': '#ffffff','font-weight': 'bold','border-radius': '4px','-webkit-border-radius': '4px','-moz-border-radius': '4px','z-index': '1000',opacity: 0.85}).appendTo("body").fadeIn(100);
}


function cancelBubbling(e) 
{
	if (!e) { var e = window.event; }
	if (e) { e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } }
}



function validateDatasourceURL(urlid, componentid, btnid, txtbxid)
{
    var url = $('#' + urlid).val();
    if (url.length < 10) { return; }
    
    if (txtbxid == undefined) { txtbxid = urlid; }
    
    if (btnid) { document.getElementById(btnid).src="images/loading_sm.gif"; }
    
    $('.savebutton').attr("disabled", "true");
    $('.savebutton').removeClass("stdbutton");
    $('.savebutton').addClass("stdbutton_disabled");
    
    $.ajax({
        url: "rest.ashx?method=validateDatasourceURL&url=" + encodeURIComponent(url) + "&componentid=" + componentid,
        type: "GET",
        cache: false,
        success: function(data)
        {
            document.getElementById(urlid).className = "stdtextbox";
        
            var arrdata = data.split("|")
            if (arrdata.length == 3)
            {
                if (arrdata[0] == "0")
                {
                    if (btnid) { document.getElementById(btnid).src="images/icon_validate_error.png"; }
                
                    document.getElementById(txtbxid).className = "stdtextbox_error";
                    var error = "The data source you have entered is not valid.";
                    if (arrdata[1].length > 0) { error = error + " " + arrdata[1]; }
                    alert(error);
                    
                    if (btnid)  { setTimeout(function () { document.getElementById(btnid).src="images/icon_validate.png"; }, 3000); }
                }
                else
                {
                    if (btnid) { document.getElementById(btnid).src="images/icon_validate_ok.png"; }
                
                    if (arrdata[2].length > 0) { $('#' + txtbxid).val(arrdata[2]); }
                
                    $('#' + txtbxid).addClass("stdtextbox_good");
                    setTimeout(function () {  $('#' + txtbxid).removeClass("stdtextbox_good"); document.getElementById(btnid).src="images/icon_validate.png"; }, 3000);
                }
            }
            
            $('.savebutton').removeAttr("disabled");
            $('.savebutton').removeClass("stdbutton_disabled");
            $('.savebutton').addClass("stdbutton");
        }
    });
    
}


function selectRFBase(urlid)
{
    if (!document.getElementById(urlid)) { return; }
    
    if (!document.getElementById('divRFBase'))
    {
        var s = "";
        s = s + "<div id=\"divRFBase\" style=\"display: none; min-width: 250px; position: absolute; z-index:500; background-color: #ffffff; padding: 6px; border: 1px solid #999999; border-radius: 4px; -webkit-border-radius: 4px; -moz-border-radius: 4px; -webkit-box-shadow: 3px 3px 3px rgba(0, 0, 0, 0.3); -moz-box-shadow: 3px 3px 3px rgba(0, 0, 0, 0.3); box-shadow: 3px 3px 3px rgba(0, 0, 0, 0.3);\">";
        s = s + "<img src=\"images/divit_999_up.png\" style=\"position: absolute; top: -7px ; left: 12px;\">";
        s = s + "<div id=\"divRFBase_inner\" style=\"padding: 5px; max-height: 250px; overflow: auto;\"><div style=\"text-align: center; width: 95%; padding: 5px;\"><img src=\"images/loading_sm.gif\"/><br>Loading</div></div>";
        s = s + "</div>";
        
        var div = document.createElement("div");
        div.innerHTML = s;
        document.body.appendChild(div);
    }
    
    
    $(document).bind("mousedown", function(e){
        if (e.target)
        {
            var hide = true;
            
            if (e.target.id.indexOf('divRFBaseSelector_') > -1)
            {
                hide = false;
                setTimeout(function () {$('#divRFBase').fadeOut('fast'); $(this).unbind(e); }, 250);
            }
            else
            {
                if (e.target.id.indexOf('divRFBase') > -1) { hide = false; }
                else if (e.target.parentNode)
                {
                    if (e.target.parentNode.id.indexOf('divRFBase') > -1) { hide = false; }
                    else if (e.target.parentNode.parentNode) { if (e.target.parentNode.parentNode.id.indexOf('divRFBase') > -1) { hide = false; }}
                }
            }
            
            if (hide == true) { $('#divRFBase').hide(); $(this).unbind(e); }
        }
    });
    
    $(document).bind("keydown", function(e){
        if (e.keyCode) { if (e.keyCode == 27) { $('#divRFBase').hide(); $(this).unbind(e); } }
    });
    
    var offset = $('#' + urlid).offset();
    document.getElementById('divRFBase').style.top = (offset.top + $('#' + urlid).height() + 12) + 'px';
    document.getElementById('divRFBase').style.left = offset.left + 'px';
    document.getElementById('divRFBase').style.width = ($('#' + urlid).width() - 4) + 'px';
    
    $('#divRFBase').fadeIn('fast');
    
    $.ajax({
      url: "rest.ashx?method=getRFBaseTables",
      type: "GET",
      cache: false,
      success: function(xml)
      {
        var tables = xml.documentElement.getElementsByTagName("table");
        if (tables.length > 0)
        {
            var r = "<div style=\"margin-bottom: 4px;\" class=\"textp2b\">Red Foundry Bases</div>";
            r = r + "<div>";
            for (var i = 0; i < tables.length; i++)
            {
                r = r + "<div id=\"divRFBaseRow_" + tables[i].getAttribute("id") + "\" class=\"listitem\"><span id=\"divRFBaseSelector_" + tables[i].getAttribute("id") + "\" onclick=\"$('#" + urlid + "').val('" + tables[i].getAttribute("url") + "')\">" + tables[i].getAttribute("display") + "</span></div>";
            }
            r = r + "</div>";
            document.getElementById('divRFBase_inner').innerHTML = r;
        }
        else
        {
            document.getElementById('divRFBase_inner').innerHTML = "<div style=\"text-align: center; width: 95%; padding: 10px;\">You do not current have any Red Foundry Bases created.<br><br><a href=\"rfbase.aspx\" target=\"_blank\">Create a Red Foundry Base</a></div>";
        }
      }
    });
    
}



function viewDatasourceStructure(urlid)
{
    var url = $('#' + urlid).val();
    if (url.length < 10) { return; }
    showModalWindowiFrame('XML Data', 'dialog_xmlsyntax.aspx?url=' + escape(url), 600, 900);
}



function setPageMessengerUnsaved()
{
    setPageMessanger('<span class=\"yellowbox\" class=\"textm2\"><b>Unsaved changes</b>, click the Save button below.</span>');
    $('#divSavePageComponentSettings').html('<span class=\"yellowbox\">Unsaved changes</span>');$('#divSavePageComponentSettings').show();
}


function setPageMessanger(html)
{
    $(document).ready(function()
    {
        $('#PageMessanger').html(html);
    });
}



function validateAudioStreamURL(urlid, btnid)
{
    var url = $('#' + urlid).val();
    if (url.length < 10) { return; }
    
    if (btnid) 
    { 
        document.getElementById(btnid).src="images/loading_sm.gif"; 
    }
    
    $('.savebutton').attr("disabled", "true");
    $('.savebutton').removeClass("stdbutton");
    $('.savebutton').addClass("stdbutton_disabled");
    
    $.ajax({
        url: "rest.ashx?method=validateAudioStreamURL&url=" + encodeURIComponent(url),
        type: "GET",
        cache: false,
        success: function(data)
        {
            document.getElementById(urlid).className = "stdtextbox";
        
            var arrdata = data.split("|")
            if (arrdata.length == 3)
            {
                if (arrdata[0] == "0")
                {
                    if (btnid) 
                    {
                        document.getElementById(btnid).src="images/icon_validate_error.png";
                    }
                
                    document.getElementById(urlid).className = "stdtextbox_error";
                    var error = "The audio stream you have entered is not valid.";
                    if (arrdata[1].length > 0) { error = error + " " + arrdata[1]; }
                    alert(error);
                    
                    if (btnid) 
                    {
                        setTimeout(function () 
                        {
                            document.getElementById(btnid).src="images/icon_validate.png";
                        }, 3000);
                    }
                }
                else
                {
                    if (btnid) 
                    {
                        document.getElementById(btnid).src="images/icon_validate_ok.png";
                    }
                
                    if (arrdata[2].length > 0)
                    {
                        $('#' + urlid).val(arrdata[2]);
                    }
                
                    $('#' + urlid).addClass("stdtextbox_good");
                    setTimeout(function () 
                    { 
                        $('#' + urlid).removeClass("stdtextbox_good");
                        document.getElementById(btnid).src="images/icon_validate.png";
                    }, 3000);
                }
            }
            
            $('.savebutton').removeAttr("disabled");
            $('.savebutton').removeClass("stdbutton_disabled");
            $('.savebutton').addClass("stdbutton");
        }
    });
    
}


function loadFeed(feedurl, containerid)
{
    var container = document.getElementById(containerid);
    if (container)
    {
        var feed = new google.feeds.Feed(feedurl);
        feed.load(function(result) 
        {
            if (!result.error) 
            {
                container.innerHTML = '';
                for (var i = 0; i < result.feed.entries.length; i++) 
                {
                    var entry = result.feed.entries[i];
                    var divEntry = document.createElement("div");
                    var dts = '';
                    if (entry.publishedDate.length > 5) {dts = dateFormat(new Date(entry.publishedDate), "dddd, mmmm dS, yyyy, h:MM:ss TT");}
                    divEntry.innerHTML = '<div style="margin-top: 5px; margin-bottom: 10px;"><div><a href="' + entry.link + '" target="_blank">' + entry.title + '</a></div><div class="textm1">' + entry.contentSnippet + '</div><div class="exampletext">' + dts + '</div></div>';
                    container.appendChild(divEntry);
                    if (i >= 10) { break; }
                }
            }
            else
            {
                container.innerHTML = 'No new items.';
            }
        });
    }
}



var RFBaseEditData_lnkpostid = "";
var RFBaseEditData_itemid = "";
var RFBaseEditData_valueid = "";

function RFBaseEditData()
{
    this.ItemID = "";
    this.ValueID = "";
    this.DataType = "";
    this.OriginalValue = "";
    
    this.dataholderid = "";
    this.dataid = "";
    
    RFBaseEditData.prototype.Register = function( itemid, valueid, datatype, val )
	{
	    this.ItemID = itemid;
	    this.ValueID = valueid;
	    this.DataType = datatype;
	    this.OriginalValue = val;
	    
	    this.dataholderid = 'dataholder_' + itemid + '_' + valueid;
        this.dataid = 'data_' + itemid + '_' + valueid;
	    
	    $('#' + this.dataholderid).bind('click', {rfbaseeditdata: this}, function(e){
            e.data.rfbaseeditdata.Hide();
            
            $('#' + e.data.rfbaseeditdata.dataholderid).css('border-color', '#118BD8');
            
            RFBaseEditData_itemid = e.data.rfbaseeditdata.ItemID;
            RFBaseEditData_valueid = e.data.rfbaseeditdata.ValueID;
            
            if (e.data.rfbaseeditdata.DataType == '5')
            {
                var dataholderid_height = $('#' + e.data.rfbaseeditdata.dataholderid).height();
                var dataholderid_width = $('#' + e.data.rfbaseeditdata.dataholderid).width();
                $('#divDataEdit').height((dataholderid_height >= 48 ? dataholderid_height : 48) + 6);
                $('#divDataEdit').width((dataholderid_width >= 106 ? dataholderid_width : 106) + 8);
                
                var dataholderid_position = $('#' + e.data.rfbaseeditdata.dataholderid).position();
                $('#divDataEdit').css( { top: dataholderid_position.top, left: dataholderid_position.left })
                $('#divDataEdit').show();
            
                $('#divDataEditType_Media').show();
                
                document.getElementById('divDataEditType_Media_img').src=(e.data.rfbaseeditdata.OriginalValue.length > 0 ? e.data.rfbaseeditdata.OriginalValue : "images/icon48_noimage.png");
                
                $('#divDataEditType_Media').bind('click', {rfbaseeditdata: e.data.rfbaseeditdata}, function(e){
                    showModalWindow('Change Image', '<div style="padding: 0px;"><iframe src="dialog_uploadmedia.aspx?usermedia=1&firecomplete=parent.document.getElementById(\'divDataEditType_Media_update\').style.display=\'none\'; parent.document.getElementById(\'divDataEditType_Media_updateloading\').style.display=\'block\'; parent.__doPostBack(\'' + RFBaseEditData_lnkpostid + '\',\'editdataattribute:' + RFBaseEditData_itemid + '|' + RFBaseEditData_valueid + '|' + e.data.rfbaseeditdata.DataType + '|MEDIAID\');" width="100%" height="600" frameborder=0 align=middle scrolling=no>loading...</iframe></div>', 640, 600);
                    $('#divDataEditType_Media').unbind('click');
                });
            }
            else if (e.data.rfbaseeditdata.DataType == '4')
            {
                var dataholderid_height = $('#' + e.data.rfbaseeditdata.dataholderid).height();
                var dataholderid_width = $('#' + e.data.rfbaseeditdata.dataholderid).width();
                $('#divDataEdit').height(dataholderid_height + 6);
                $('#divDataEdit').width(dataholderid_width + 8);
                
                var dataholderid_position = $('#' + e.data.rfbaseeditdata.dataholderid).position();
                $('#divDataEdit').css( { top: dataholderid_position.top, left: dataholderid_position.left })
                $('#divDataEdit').show();
            
                $('#divDataEditType_File').show();
               
                $('#divDataEditType_File').bind('click', {rfbaseeditdata: e.data.rfbaseeditdata}, function(e){
                    showModalWindow('Change File', '<div style="padding: 0px;"><iframe src="dialog_uploadfile.aspx?usermedia=1&firecomplete=parent.document.getElementById(\'divDataEditType_File_update\').style.display=\'none\'; parent.document.getElementById(\'divDataEditType_File_updateloading\').style.display=\'block\'; parent.__doPostBack(\'' + RFBaseEditData_lnkpostid + '\',\'editdataattribute:' + RFBaseEditData_itemid + '|' + RFBaseEditData_valueid + '|' + e.data.rfbaseeditdata.DataType + '|FILEID\');" width="100%" height="360" frameborder=0 align=middle scrolling=no>loading...</iframe></div>', 400, 600);
                    $('#divDataEditType_File').unbind('click');
                });
            }
            
        });
        
        $('#' + this.dataholderid).bind('dblclick', {rfbaseeditdata: this}, function(e){
            e.data.rfbaseeditdata.Hide();
            
            RFBaseEditData_itemid = e.data.rfbaseeditdata.ItemID;
            RFBaseEditData_valueid = e.data.rfbaseeditdata.ValueID;
            
            var dataholderid_height = $('#' + e.data.rfbaseeditdata.dataholderid).height();
            var dataholderid_width = $('#' + e.data.rfbaseeditdata.dataholderid).width();
            $('#divDataEdit').height(dataholderid_height + 6);
            $('#divDataEdit').width(dataholderid_width + 8);
            
            var dataholderid_position = $('#' + e.data.rfbaseeditdata.dataholderid).position();
            $('#divDataEdit').css( { top: dataholderid_position.top, left: dataholderid_position.left })
            $('#divDataEdit').show();
            
            if (e.data.rfbaseeditdata.DataType == '5')
            {}
            else if (e.data.rfbaseeditdata.DataType == '4')
            {}
            else
            {
                 $('#divDataEditType_String').show();
                 $('#divDataEditType_String_txtarea').height(dataholderid_height);
                 $('#divDataEditType_String_txtarea').width(dataholderid_width);
                 $('#divDataEditType_String_txtarea').val(e.data.rfbaseeditdata.OriginalValue);
                 
                 setSelectionRange(document.getElementById('divDataEditType_String_txtarea'), e.data.rfbaseeditdata.OriginalValue, e.data.rfbaseeditdata.OriginalValue.length);
                 
                 $('#divDataEditType_String_txtarea').bind('blur', {rfbaseeditdata: e.data.rfbaseeditdata}, function(e){
                    if (e.data.rfbaseeditdata.OriginalValue != $('#divDataEditType_String_txtarea').val())
                    {
                        e.data.rfbaseeditdata.Hide();
                        document.getElementById(e.data.rfbaseeditdata.dataholderid).innerHTML = '<div><img src="images/loading_sm.gif" /></div>';
                        __doPostBack(RFBaseEditData_lnkpostid,'editdataattribute:' + RFBaseEditData_itemid + '|' + RFBaseEditData_valueid + '|' + e.data.rfbaseeditdata.DataType + '|' + $('#divDataEditType_String_txtarea').val() );
                    }
                    else
                    {
                        e.data.rfbaseeditdata.Hide();
                    }
                    
                    $('#divDataEditType_String_txtarea').unbind('blur');
                 });
            }
            
        });
	}
	
	
	RFBaseEditData.prototype.Hide = function()
	{
	    $('#divDataEdit').hide();
	    $('.divDataEditType').hide();
        $('.dataholder').css('border-color', 'transparent');
	}
}

function setSelectionRange(input, selectionStart, selectionEnd) {
  if (input.setSelectionRange) {
    input.focus();
    input.setSelectionRange(selectionStart, selectionEnd);
  }
  else if (input.createTextRange) {
    var range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  }
}

var DataSourceMapper_containerid = "";
var DataSourceMapper_txtid = "";
var DataSourceMapper_preval = "";
var DataSourceMapper_postval = "";
function showDataSourceMapper(containerid, txtid, all, preval, postval)
{
    if( $('#DataSourceMapper').is(':visible') && DataSourceMapper_containerid == containerid ) {
        hideDataSourceMapper();
        return;
    }
    
    hideDataSourceMapper();
    
    if (all == true)
    {
        $('#mapsub').hide();
        $('#mapall').show();
    }
    else
    {
        $('#mapall').hide();
        $('#mapsub').show();
    }
    
    DataSourceMapper_containerid = containerid;
    DataSourceMapper_txtid = txtid;
    DataSourceMapper_preval = preval;
    DataSourceMapper_postval = postval;
    
    var containerid_height = $('#' + containerid).height();
    var containerid_position = $('#' + containerid).position();
    $('#DataSourceMapper').css( { top: containerid_position.top + containerid_height + 9, left: containerid_position.left })
    $('#DataSourceMapper').slideDown('fast');
    $('#' + containerid).addClass('datasourcemapperselector_selected');
}

function hideDataSourceMapper()
{
    $('#DataSourceMapper').hide();
    $('.datasourcemapperselector').removeClass('datasourcemapperselector_selected');
}

function showVideo(url,height,width)
{
    var left = parseInt((screen.availWidth/2) - (width/2));
    var top = parseInt((screen.availHeight/2) - (height/2));
    var windowFeatures = "width=" + width + ",height=" + height + ",status,resizable,left=" + left + ",top=" + top + "screenX=" + left + ",screenY=" + top;
    videoWin = window.open(url, "videoWin", windowFeatures);
}



(function($){
    $.fn.fontNameSel = function(settings) 
    {
        var fonts = new Array('AmericanTypewriter','AmericanTypewriter-Bold','AppleGothic','ArialMT','Arial-BoldMT','Arial-BoldItalicMT','Arial-ItalicMT','ArialRoundedMTBold','Courier','Courier Bold Oblique','Courier-Oblique','Courier-Bold','CourierNewPS-BoldMT','CourierNewPS-ItalicMT','CourierNewPS-BoldItalicMT','CourierNewPSMT','DBLCDTempBlack','Georgia-Bold','Georgia','Georgia-BoldItalic','Georgia-Italic','Helvetica-Oblique','Helvetica-BoldOblique','Helvetica','Helvetica-Bold','HelveticaNeue','HelveticaNeue-Bold','HiraKakuProN-W6','interval-light.otf','interval-ultra-light.otf','interval.otf','MarkerFelt-Thin','STHeitiTC-Light','STHeitiTC-Medium','STHeitiSC-Medium','STHeitiSC-Light','STHeitiK-Medium','STHeitiK-Light','STHeitiJ-Medium','STHeitiJ-Light','TimesNewRomanPSMT','TimesNewRomanPS-BoldMT','TimesNewRomanPS-BoldItalicMT','TimesNewRomanPS-ItalicMT','TrebuchetMS-Italic','TrebuchetMS','Trebuchet-BoldItalic','TrebuchetMS-Bold','Verdana-Bold','Verdana-BoldItalic','Verdana','Verdana-Italic','Zapfino' );
        
        return this.each(function()
        {
            var sel = this;
            $.each(fonts, function(i, item) 
            {
                $(sel).append('<option value="' + item + '">' + item.split(',')[0] + '</option>');
                if(item == settings.value)
                {
                    $(sel).children('option:last').attr('selected', 'selected');
                }
            })
            
            $(sel).change(function(){
                var selval = $(sel).find(":selected").val();
                $('#' + settings.hdn).val(selval);
            });
        });
        
    };
})( jQuery );

(function($){
    $.fn.fontSizeSel = function(settings) 
    {
        return this.each(function()
        {
            var sel = this;
            for (var i = 10; i <= 200; i++)
            {
                if (i <= 50 || (i > 50 && i <= 100 && i%2==0) || (i > 100 && i%5==0))
                {
                    $(sel).append('<option value="' + i + '">' + i + 'pt</option>');
                    if(i == settings.value)
                    {
                        $(sel).children('option:last').attr('selected', 'selected');
                    }
                }
            }
            
            $(sel).change(function(){
                var selval = $(sel).find(":selected").val();
                $('#' + settings.hdn).val(selval);
            });
        });
        
    };
})( jQuery );


var arrNavigateValues = null;
var curNavigateValue = '';
function registerNavigateValues(parentdivid)
{
    $('<div id="menuNaviagteValues" style="display: none; width: 180px; min-width: 180px; position: absolute;z-index:500; background-color: #ffffff; padding: 6px; border: 1px solid #999999; border-radius: 4px; -webkit-border-radius: 4px; -moz-border-radius: 4px; -webkit-box-shadow: 3px 3px 3px rgba(0, 0, 0, 0.3); -moz-box-shadow: 3px 3px 3px rgba(0, 0, 0, 0.3); box-shadow: 3px 3px 3px rgba(0, 0, 0, 0.3);"><img src="images/divit_999_up.png" style="position: absolute; top: -7px ; left: 12px;"><div id="menuNaviagteValues_inner" style="max-height: 350px; overflow: auto;"></div></div>').appendTo('#' + parentdivid);
    
    $(document).bind("mousedown", function(e){
        if ($(e.target).parents().is('#menuNaviagteValues') == false) {
            if (e.target.id != curNavigateValue)
            {
                $('#menuNaviagteValues').hide();
                curNavigateValue = '';
            }
        }
    });
}

function registerNavigateValue(divid, typ)
{
    window.setTimeout(function() {
        var me = $('#' + divid);
        
        $('#' + divid).bind('click', {divid: divid}, function(e){
            if( $('#menuNaviagteValues').is(':visible') || curNavigateValue == e.data.divid )
            {
                $('#menuNaviagteValues').slideUp('fast');
                curNavigateValue = '';
            }
            else
            {
                curNavigateValue = e.data.divid;
                var s = '';
                
                if (typ != 'none') {
                    if (arrNavigateValues != null) {
                        if (arrNavigateValues.length > 0) { 
                            s = s + '<div class="exampletext">Form Parameters</div>';
                            for (var i = 0; i < arrNavigateValues.length; i++)
                            {
                                s = s + '<div class="listitem" onclick="$(\'#' + e.data.divid + '\').val(\'[form:' + arrNavigateValues[i].nam + ']\');$(\'#menuNaviagteValues\').slideUp(\'fast\'); curNavigateValue=\'\';" title="[form:' + arrNavigateValues[i].nam + ']">&nbsp;<b>' + arrNavigateValues[i].nam.replace('user-','') + '</b>&nbsp;&nbsp;<span class="exampletext">' + arrNavigateValues[i].val + '</span></div>';
                            }
                        }
                    }
                }
                
                if (typ != 'nonsc') {
                    arrShortCodes = [ { nam: 'User Latitude', val: '[app:user-lat]' }, { nam: 'User Longitude', val: '[app:user-lon]' }, { nam: 'User Language', val: '[app:user-language]' }, { nam: 'App Version', val: '[app:app-version]' }, { nam: 'Screen Width', val: '[app:screen-width]' }, { nam: 'Screen Height', val: '[app:screen-height]' }, { nam: 'Device ID', val: '[app:device-id]' }, { nam: 'Device Model', val: '[app:device-model]' }];
                    s = s + '<div style="margin-top: ' + (typ == 'none' ? '0' : '10') + 'px;" class="exampletext">App Short Codes</div>';
                    for (var j = 0; j < arrShortCodes.length; j++)
                    {
                        s = s + '<div class="listitem textm1" onclick="$(\'#' + e.data.divid + '\').val(\'' + arrShortCodes[j].val + '\');$(\'#menuNaviagteValues\').slideUp(\'fast\'); curNavigateValue=\'\';">&nbsp;' + arrShortCodes[j].nam + '&nbsp;&nbsp;<span class="exampletext">' + arrShortCodes[j].val + '</span></div>';
                    }
                }
                $('#menuNaviagteValues_inner').html(s);
                
                var divid_height = $('#' + e.data.divid).height();
                var divid_width = $('#' + e.data.divid).width();
                var divid_position = $('#' + e.data.divid).position();
                $('#menuNaviagteValues').css( { top: divid_position.top + divid_height + 12, left: divid_position.left, width: divid_width - 4 })
                $('#menuNaviagteValues').slideDown('fast');
            }
        });
    }, 1000);
}


var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,timezoneClip = /[^-+\dA-Z]/g,pad = function (val, len) {val = String(val);len = len || 2;while (val.length < len) val = "0" + val;return val;};
	return function (date, mask, utc) {
		var dF = dateFormat;
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {mask = date;date = undefined;}
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");
		mask = String(dF.masks[mask] || mask || dF.masks["default"]);
		if (mask.slice(0, 4) == "UTC:") { mask = mask.slice(4); utc = true;}
		var	_ = utc ? "getUTC" : "get",	d = date[_ + "Date"](),	D = date[_ + "Day"](),m = date[_ + "Month"](),y = date[_ + "FullYear"](),H = date[_ + "Hours"](),M = date[_ + "Minutes"](),s = date[_ + "Seconds"](),L = date[_ + "Milliseconds"](),o = utc ? 0 : date.getTimezoneOffset(),flags = {d:d,dd:pad(d),ddd:dF.i18n.dayNames[D],dddd: dF.i18n.dayNames[D + 7],m:m + 1,mm:pad(m + 1),mmm:dF.i18n.monthNames[m],mmmm: dF.i18n.monthNames[m + 12],yy:String(y).slice(2),yyyy: y,h:H % 12 || 12,hh:pad(H % 12 || 12),H:H,HH:pad(H),M:M,MM:pad(M),s:s,ss:pad(s),l:pad(L, 3),L:pad(L > 99 ? Math.round(L / 10) : L),t:H < 12 ? "a"  : "p",tt:H < 12 ? "am" : "pm",T:H < 12 ? "A"  : "P",TT:H < 12 ? "AM" : "PM",Z:utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),o:(o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),S:["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]};
		return mask.replace(token, function ($0) { return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1); });
	};
}();
dateFormat.masks = {"default":"ddd mmm dd yyyy HH:MM:ss",shortDate:"m/d/yy",mediumDate:"mmm d, yyyy",longDate:"mmmm d, yyyy",fullDate:"dddd, mmmm d, yyyy",shortTime:"h:MM TT",mediumTime:"h:MM:ss TT",longTime:"h:MM:ss TT Z",isoDate:"yyyy-mm-dd",isoTime:"HH:MM:ss",isoDateTime:"yyyy-mm-dd'T'HH:MM:ss",isoUtcDateTime:"UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"};
dateFormat.i18n = {dayNames: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat","Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],monthNames: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec","January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]};
Date.prototype.format = function (mask, utc) {return dateFormat(this, mask, utc);};
