
 /*=====================================================
 ================= realPopups.js ======================
 =====================================================*/ 
//openPopup(tcUrl, tnWidth, tnHeight, tcWindowName, tlScrolled, tnPosX, tnPosY, tnPosOffsetX, tnPosOffsetY)

// Sagalaba loga izmeru pie resaiza
function winSaveSize()
{
	var lcName = window.name;
	var lnWidth = GetWindow_Width();
	var lnHeight = GetWindow_Height();
	SetCookie('WinSize_' + lcName, lnWidth + 'x' + lnHeight, 'forever');
} 

function openPopup_EditText(tnID, tcField, tcTable, tnWidth)
{
	var lcUrl = '/cms/visio/popups/textEdit.php?tran_id='+tnID+'&task=Edit&table='+tcTable+'&field='+tcField+'&width='+tnWidth;
	openPopup(lcUrl, 800, 600);
}
function openPopup_ChapterMoveOut(tcUrl)				
{
	openPopup('/cms/popup/selectChapterParent.php?'+tcUrl, 400, 500, 'ChapterMoveOut', true);
}

function OpenPopup_EditChapter(tcUrl)
{
	openPopup('/cms/popup/editChapter.php?'+tcUrl, 400, 215, 'EditChaptet');
}
function OpenPopup_EditCatalog(tcUrl)
{
	openPopup('/cms/popup/editCatalog.php?'+tcUrl, 500, 205, 'EditCatalog');
}
function OpenPopup_MoveHere(tcUrl, tnObjectCount)
{
	if(typeof(tnObjectCount) != 'undefined')
	{
		if(tnObjectCount > 25)
			tnObjectCount = 25;
	}
	else
	{
		tnObjectCount = 25;
	}

	var lnHeight = (tnObjectCount+1) * 19 + 150;
	openPopup('/cms/popup/listMoveHere.php?'+tcUrl, 400, lnHeight, 'MoveHere', true);
}
function OpenPopup_MoveChapter(tcUrl)
{
	openPopup('/cms/popup/moveChapter.php?'+tcUrl, 400, 500, 'MoveChapter', true, true);
}
function OpenPopup_EditFile(tcUrl)
{
	openPopup('/cms/popup/editFile.php?'+tcUrl, 400, 220, 'EditChapter');
}
function OpenPopup_EditPriceText(tcUrl)
{
	openPopup('/cms/popup/editPriceText.php?'+tcUrl, 400, 230, 'EditPriceText');
}

function OpenPopup_EditSimpleTextTitle(tcUrl)
{
	openPopup('/cms/popup/editSimpleTextTitle.php?'+tcUrl, 400, 190, 'EditSimpleTextTitle');
}


function OpenPopup_EditTeacherPhoto(tcUrl)
{
	openPopup('/cms/popup/editTeacherPhoto.php?'+tcUrl, 400, 190, 'EditTeacherPhoto');	
}
function OpenPopup_EditBanner(tcUrl)
{
	openPopup('/cms/popup/editBanner.php?'+tcUrl, 400, 365, 'EditBanner');
}
function OpenPopup_EditGalleryPicture(tcUrl)
{
	openPopup('/cms/popup/editGalleryPicture.php?'+tcUrl, 480, 240, 'EditGalleryPicture');
}
function OpenPopup_EditCourse(tcUrl)
{
	openPopup('/cms/popup/editCourse.php?'+tcUrl, 400, 220, 'EditCourse');
}

function OpenPopup_SubscribeCourse(tcUrl)
{
	openPopup('/user/popup/subscribeCourse.php?'+tcUrl, 400, 240, 'SubscribeCourse');
}

function OpenPopup_EditSimpleTextString(tcUrl)
{
	openPopup('/cms/popup/editSimpleTextString.php?'+tcUrl, 400, 130, 'EditSimpleTextString');
}

function OpenPopup_EditSimpleTextArea(tcUrl)
{
	openPopup('/cms/popup/editSimpleTextArea.php?'+tcUrl, 400, 260, 'EditSimpleTextString');
}


function OpenPopup_GalleryPopup(tcUrl)
{
	openPopup('/user/popup/galleryPopup.php?'+tcUrl, 760, 640, 'GalleyPopup');
}

function OpenPopup_MoveCatalog(tcUrl)
{
	openPopup('/cms/popup/moveCatalog.php?'+tcUrl, 760, 640, 'MoveCatalog', true);
}
function OpenPopup_SetProductCatalog(tcUrl)
{
	openPopup('/cms/popup/setProductCatalog.php?'+tcUrl, 760, 640, 'SetProductCatalog', true);
}
function OpenPopup_EditProduct(tcUrl)
{
	openPopup('/cms/popup/editProduct.php?'+tcUrl, 800, 520, 'EditProduct', false, true);
}

function OpenPopup_QualityFilter(tcUrl)
{
	openPopup('/cms/popup/editQualityFilter.php?'+tcUrl, 400, 300, 'QualityFilter');
}
function OpenPopup_EditAttribute(tcUrl)
{
	openPopup('/cms/popup/editAttribute.php?'+tcUrl, 400, 240, 'EditBanner');
}
function OpenPopup_ViewImage(tcUrl, tnWidth, tnHeight)
{
	openPopup(''+tcUrl, tnWidth, tnHeight, 'ViewImage');
}

function OpenPopup_MoveHereProduct(tcUrl, tnObjectCount)
{
	if(typeof(tnObjectCount) != 'undefined')
	{
		if(tnObjectCount > 25)
			tnObjectCount = 25;
	}
	else
	{
		tnObjectCount = 25;
	}

	var lnHeight = (tnObjectCount+1) * 19 + 150;
	openPopup('/cms/popup/listMoveHereProduct.php?'+tcUrl, 400, lnHeight, 'MoveHereProduct', true);
}
function OpenPopup_SetLinkedProductsCatalog(tcUrl)
{
	openPopup('/cms/popup/setLinkedProducts.php?'+tcUrl, 760, 640, 'SetLinkedProducts', true, true);
}
function OpenPopup_SetBannerCatalog(tcUrl)
{
	openPopup('/cms/popup/setBannerCatalog.php?'+tcUrl, 760, 640, 'SetBannerCatalog', true);
}

function OpenPopup_SetBannerChapter(tcUrl)
{
	openPopup('/cms/popup/setBannerChapter.php?'+tcUrl, 760, 640, 'SetBannerCatalog', true);
}

function OpenPopup_EditClientFiz(tcUrl)
{
	openPopup('/cms/popup/editClient.php?'+tcUrl, 450, 440, 'EditClientFiz', false, false);
}

function OpenPopup_EditClientJure(tcUrl)
{
	openPopup('/cms/popup/editClient.php?'+tcUrl, 450, 480, 'EditClientJure', false, false);
}

function OpenPopup_EditOrder(tcUrl)
{
	openPopup('/cms/popup/editOrder.php?'+tcUrl, 650, 550, 'EditOrderJure', true, true);
}
function OpenPopup_AddOrderProduct(tcUrl)
{
	openPopup('/cms/popup/addOrderProduct.php?'+tcUrl, 450, 450, 'AddOrderProduct', true, true);
}
function OpenPopup_SaveDicItem(tcUrl)
{
	openPopup('/cms/popup/saveDicItem.php?'+tcUrl, 10, 10, 'SaveDicItem', false, false);
}
function OpenPopup_EditDictItem(tcUrl)
{
	openPopup('/cms/popup/editDictItem.php?'+tcUrl, 400, 300, 'EditDictItem', false, false);
}
function OpenPopup_DictFullText(tcUrl)
{
	openPopup('/cms/popup/DictFullText.php?'+tcUrl, 400, 300, 'EditDictItem', false, false);
}
function OpenPopup_AddOrderAddition(tcUrl)
{
	openPopup('/cms/popup/addOrderAddition.php?'+tcUrl, 450, 450, 'AddOrderProduct', true, true);
}

function OpenPopup_EditSkynChapter(tcUrl)
{
	openPopup('/cms/popup/editSkynChapter.php?'+tcUrl, 400, 215, 'EditSkynChapter');
}
function OpenPopup_EditSkyn(tcUrl)
{
	openPopup('/cms/popup/editSkyn.php?'+tcUrl, 650, 500, 'EditSkyn', true);
}
function OpenPopup_EditPacking(tcUrl)
{
	openPopup('/cms/popup/editPacking.php?'+tcUrl, 430, 210, 'EditPacking');
}
function OpenPopup_EditAction(tcUrl)
{
	openPopup('/cms/popup/editAction.php?'+tcUrl, 600, 280, 'EditAction');
}
function OpenPopup_EditActionProducts(tcUrl, tcActionLogicID)
{
	openPopup('/cms/popup/Actions/'+tcActionLogicID+'.php?'+tcUrl, 800, 600, 'EditAP'+tcActionLogicID, true, true);
}

function OpenPopup_PreviewSkyn(tcUrl)
{
	openPopup('/?'+tcUrl, 950, 700, 'PreviewSkyn', true, true);
}

function OpenPopup_ColorPicker(tnDestID, tcCurColor)
{
	openPopup('/cms/popup/colorPicker.php?src_id='+tnDestID+'&cur_color='+tcCurColor, 340, 320, 'ColorPicker');
}

function PrintPage(tcUrl)
{
	openPopup(tcUrl, 700, 600, 'ColorPicker', true, true, null, null, 1, 1);	
}
 /*=====================================================
 ================= cms.js ======================
 =====================================================*/ 
function UniqueID()
{
	ldDate = new Date();
	return ldDate.getTime();
}
function CenterWindow(toWin, tnWidth, tnHeight)
{
	lnX = screen.width / 2	- tnWidth / 2;
	lnY = screen.height / 2	- tnHeight / 2;
	toWin.moveTo(lnX, lnY);
}

function GetWindow_Width()
{
	return document.body.offsetWidth;
}
function GetWindow_Height()
{
	return document.body.offsetHeight;
}

function GetCenterWindow_Left(tnWidth)
{
	return screen.width / 2	- tnWidth / 2;
}
function GetCenterWindow_Top(tnHeight)
{
	return screen.height / 2	- tnHeight / 2;
}

function openPopup(tcUrl, tnWidth, tnHeight, tcWindowName, tlResizeable ,tlScrolled, tnPosX, tnPosY, tnMenu, tnBar)
{
	if(("" + tcWindowName) == "undefined")
	{
		tcWindowName = UniqueID();
	}

	tcWindowName = "popup_"+tcWindowName;

	tlResizeable 	= typeof(tlResizeable) 	== "undefined" || !tlResizeable ? false : true;
	tlScrolled	= typeof(tlScrolled) 	== "undefined" || !tlScrolled ? false : true;

	var lcScrolled 	= tlScrolled  ? 'yes' : 'no';
	var lcResizable = tlResizeable ? 'yes' : 'no'; 
	
	// Ja logam ir iespejams mainit izmerus tad ieprieksejie varetu but ieks cookie 
	if(tlResizeable)
	{
		
		var lcCookieSizes = GetCookie("WinSize_"+tcWindowName);

		if(lcCookieSizes)
		{
			var laSizes =lcCookieSizes.split('x');
			tnWidth 	= laSizes[0] - 1;
			tnHeight 	= laSizes[1] - 1;   
		}	
	}

	var lnLeft	= tnPosX != null ? tnPosX : GetCenterWindow_Left(tnWidth);
	var lnTop	= tnPosY != null ? tnPosY : GetCenterWindow_Top(tnHeight);


	var lnMenu 	= tnMenu != null ? tnMenu : '0';
	var lnBar 	= tnBar != null ? tnBar : '0';

	var lcSettings = 
		"left="			+lnLeft		+
		",top="			+lnTop		+
		",scrollbars="	+lcScrolled	+
		",resizable="	+lcResizable+
		",menubar="	+lnMenu+
		",toolbar="	+lnBar+
		",width="		+tnWidth	+
		",height="		+tnHeight;
	
	
	loWin = window.open(tcUrl, tcWindowName, lcSettings);
	loWin.focus();
}


function openPopupScrolled(tcUrl, tnWidth, tnHeight)
{
	loWin = open(tcUrl, "popup"+UniqueID(), "scrollbars=yes,resizable=no,width="+tnWidth+",height="+tnHeight+"");
	loWin.focus();
}

function editSimpleText(tcTask, tnChapterID, tcLangID, tcFieldName, tcLogicID)
{
	if(tcTask == 'edit' || tcTask == 'add')
	{
		$lcUrl = "editSimpleText.php?task=" +tcTask
			+ "&chapterID="		+ tnChapterID
			+ "&textLangID="	+ tcLangID
			+ "&field_name="	+ tcFieldName
			+ "&logic_id=" 		+ tcLogicID;
		//alert();
		openPopup($lcUrl, 650, 550);
	}
	if(tcTask == 'view')
	{
		window.location = "?text_lang_id="+tcLangID;
	}
	if(tcTask == 'drop' && AreYouSure())
	{
		window.location = "?delete_text_id="+tnChapterID;
	}
	
}

// ============== GALLERY CHAPTER
function editGalleryChapter(tnID)
{
	manageGalleryChapter("edit", tnID);
}
function deleteGalleryChapter(tnID)
{
	manageGalleryChapter("drop", tnID);
}
function addGalleryChapter(tnParentID)
{
	manageGalleryChapter("add", 0, tnParentID);
}

function manageGalleryChapter(tcTask, tnID, tnParentID)
{
	if(tcTask == "add" || tcTask == "edit" || tcTask == "drop")
	{
		lcUrl = "popup/editGalleryChapter.php?task=" + tcTask;
		if(tcTask == "add")
			lcUrl += "&parent_id=" + tnParentID;
		else
			lcUrl += "&id=" + tnID;
		openPopup(lcUrl, 500, 450);
	}
	else
	{
		window.location.href = "?task=" + tcTask + "&id=" + tnID;
	}
}
// ============== GALLERY FOLDER
function editGalleryFolder(tnID)
{
	manageGalleryFolder("edit", tnID);
}
function deleteGalleryFolder(tnID)
{
	manageGalleryFolder("drop", tnID);
}
function addGalleryFolder(tnParentID)
{
	manageGalleryFolder("add", 0, tnParentID);
}

function manageGalleryFolder(tcTask, tnID, tnParentID)
{
	if(tcTask == "add" || tcTask == "edit" || tcTask == "drop")
	{
		lcUrl = "popup/editGalleryFolder.php?task=" + tcTask;
		if(tcTask == "add")
			lcUrl += "&parent_id=" + tnParentID;
		else
			lcUrl += "&id=" + tnID;
		openPopup(lcUrl, 500, 450);
	}
	else
	{
		window.location.href = "?task=" + tcTask + "&id=" + tnID;
	}
}

 /*=====================================================
 ================= cookie.js ======================
 =====================================================*/ 
var gcLangID = 'lv';
if(GetCookie('Language'))
	gcLangID = GetCookie('Language');
//---------------------------------------------------------------------
// Function to return the value of the cookie specified by "name".

// Parameter:
//     name     String object containing the cookie name.

// Return:      String object containing the cookie value, or null if
//              the cookie does not exist.
//---------------------------------------------------------------------
function GetCookie (name)
{
    var arg  = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i    = 0;

    while (i < clen)
    {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg)
          return getCookieVal (j);
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
    }
    return null;
}
//---------------------------------------------------------------------
// Function to get a cookie.
//---------------------------------------------------------------------
function getCookieVal( offset )
{
    var endstr = document.cookie.indexOf (";", offset);

    if (endstr == -1)
        endstr = document.cookie.length;
    return unescape(document.cookie.substring(offset, endstr));
}
//---------------------------------------------------------------------
// Function to set a cookie.
//---------------------------------------------------------------------
function SetCookie( name, value, tcExpireCode )
{
    var argv    = SetCookie.arguments;
    var argc    = SetCookie.arguments.length;
    var expires	= null;
    
    switch(tcExpireCode)
    {
    	case 'session'  : expires =null;break;
    	case 'forever' : expires =null;
    		var d = new Date();
    		d.setYear(d.getYear()+1);
    		expires = d.toGMTString();
    	break;
    }

    var path    = '/';
    var domain  = null;
    var secure  = false;

    document.cookie =
        name + "=" + escape (value) +
        ((expires 	== null) ? "" 			: ("; expires=" + expires)) +
        ((path 		== null) ? "" 			: ("; path=" 	+ path)) +
        ((domain 	== null) ? "" 			: ("; domain=" 	+ domain)) +
        ((secure 	== true) ? "; secure" 	: "");
}
//---------------------------------------------------------------------
// Function to delete a cookie. (Sets expiration date)
//    name - String object containing the cookie name
//---------------------------------------------------------------------
function DeleteCookie (name)
{
    var exp  = new Date();
    var cval = GetCookie (name);

    exp.setTime (exp.getTime() - 1);  // This cookie is history
    document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}
 /*=====================================================
 ================= twitter.js ======================
 =====================================================*/ 
/**
 * remy sharp / http://remysharp.com
 * Twitter / @rem
 * http://remysharp.com/2007/05/18/add-twitter-to-your-blog-step-by-step/
 *
 * @params
 *   cssIdOfContainer: e.g. twitters
 *   options: 
 *       {
 *           id: {String} username,
 *           count: {Int} 1-20, defaults to 1 - max limit 20
 *           prefix: {String} '%name% said', defaults to blank
 *           clearContents: {Boolean} true, removes contents of element specified in cssIdOfContainer, defaults to true
 *           ignoreReplies: {Boolean}, skips over tweets starting with '@', defaults to false
 *           template: {String} HTML template to use for LI element (see URL above for examples), defaults to predefined template
 *           enableLinks: {Boolean} linkifies text, defaults to true,
 *           newwindow {Boolean} opens links in new window, defaults to false
 *           timeout: {Int} How long before triggering onTimeout, defaults to 10 seconds if onTimeout is set
 *           onTimeoutCancel: {Boolean} Completely cancel twitter call if timedout, defaults to false
 *           onTimeout: {Function} Function to run when the timeout occurs. Function is bound to element specified with 
 *           cssIdOfContainer (i.e. 'this' keyword)
 *           callback: {Function} Callback function once the render is complete, doesn't fire on timeout
 *
 *      CURRENTLY DISABLED DUE TO CHANGE IN TWITTER API:
 *           withFriends: {Boolean} includes friend's status
 *
 *       }
 *
 * @license MIT (MIT-LICENSE.txt)
 * @version 1.13.1 - Number of fixes to ify, and fixed date parsing in Opera and 12AM issue
 * @date $Date: 2009-08-25 09:45:35 +0100 (Tue, 25 Aug 2009) $
 */

// to protect variables from resetting if included more than once
if (typeof renderTwitters != 'function') (function () {
    /** Private variables */
    
    // only used for the DOM ready, since IE & Safari require special conditions
    var browser = (function() {
        var b = navigator.userAgent.toLowerCase();

        // Figure out what browser is being used
        return {
            webkit: /(webkit|khtml)/.test(b),
            opera: /opera/.test(b),
            msie: /msie/.test(b) && !(/opera/).test(b),
            mozilla: /mozilla/.test(b) && !(/(compatible|webkit)/).test(b)
        };
    })();

    var guid = 0;
    var readyList = [];
    var isReady = false;
    
    var monthDict = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    
    /** Global functions */
    
    // based on Dustin Diaz's ify, but with my fixes :-)
    window.ify = function() {
      var entities = {
          '"' : '&quot;',
          '&' : '&amp;',
          '<' : '&lt;',
          '>' : '&gt;'
      };

      return {
        "link": function(t) {
          return t.replace(/[a-z]+:\/\/[a-z0-9-_]+\.[a-z0-9-_:~%&\?\/.=]+[^:\.,\)\s*$]/ig, function(m) {
            return '<a href="' + m + '">' + ((m.length > 25) ? m.substr(0, 24) + '...' : m) + '</a>';
          });
        },
        "at": function(t) {
          return t.replace(/(^|[^\w]+)\@([a-zA-Z0-9_]{1,15})/g, function(m, m1, m2) {
            return m1 + '@<a href="http://twitter.com/' + m2 + '">' + m2 + '</a>';
          });
        },
        "hash": function(t) {
          return t.replace(/(^|[^\w'"]+)\#([a-zA-Z0-9_]+)/g, function(m, m1, m2) {
            return m1 + '#<a href="http://search.twitter.com/search?q=%23' + m2 + '">' + m2 + '</a>';
          });
        },
        "clean": function(tweet) {
          return this.hash(this.at(this.link(tweet)));
        }
      };
    }();
    
    // to create a public function within our private scope, we attach the 
    // the function to the window object
    window.renderTwitters = function (obj, options) {
        // private shortcuts
        function node(e) {
            return document.createElement(e);
        }
        
        function text(t) {
            return document.createTextNode(t);
        }

        var target = document.getElementById(options.twitterTarget);
        var data = null;
        var ul = node('ul'), li, statusSpan, timeSpan, i, max = obj.length > options.count ? options.count : obj.length;
        
        for (i = 0; i < max && obj[i]; i++) {
            data = getTwitterData(obj[i]);
                        
            if (options.ignoreReplies && obj[i].text.substr(0, 1) == '@') {
                max++;
                continue; // skip
            }
            
            li = node('li');
            
            if (options.template) {
                li.innerHTML = options.template.replace(/%([a-z_\-\.]*)%/ig, function (m, l) {
                    var r = data[l] + "" || "";
                    if (l == 'text' && options.enableLinks) r = ify.clean(r);
                    return r;
                });
            } else {
                statusSpan = node('span');
                statusSpan.className = 'twitterStatus';
                timeSpan = node('span');
                timeSpan.className = 'twitterTime';
                statusSpan.innerHTML = obj[i].text; // forces the entities to be converted correctly

                if (options.enableLinks == true) {
                    statusSpan.innerHTML = ify.clean(statusSpan.innerHTML);
                }

                timeSpan.innerHTML = relative_time(obj[i].created_at);

                if (options.prefix) {
                    var s = node('span');
                    s.className = 'twitterPrefix';
                    s.innerHTML = options.prefix.replace(/%(.*?)%/g, function (m, l) {
                        return obj[i].user[l];
                    });
                    li.appendChild(s);
                    li.appendChild(text(' ')); // spacer :-(
                }

                li.appendChild(statusSpan);
                li.appendChild(text(' '));
                li.appendChild(timeSpan);
            }
            
            if (options.newwindow) {
                li.innerHTML = li.innerHTML.replace(/<a href/gi, '<a target="_blank" href');
            }
            
            ul.appendChild(li);
        }

        if (options.clearContents) {
            while (target.firstChild) {
                target.removeChild(target.firstChild);
            }
        }

        target.appendChild(ul);
        
        if (typeof options.callback == 'function') {
            options.callback();
        }
    };
    
    window.getTwitters = function (target, id, count, options) {
        guid++;

        if (typeof id == 'object') {
            options = id;
            id = options.id;
            count = options.count;
        } 

        // defaulting options
        if (!count) count = 1;
        
        if (options) {
            options.count = count;
        } else {
            options = {};
        }
        
        if (!options.timeout && typeof options.onTimeout == 'function') {
            options.timeout = 10;
        }
        
        if (typeof options.clearContents == 'undefined') {
            options.clearContents = true;
        }
        
        // Hack to disable withFriends, twitter changed their API so this requires auth
        // http://getsatisfaction.com/twitter/topics/friends_timeline_api_call_suddenly_requires_auth
        if (options.withFriends) options.withFriends = false;

        // need to make these global since we can't pass in to the twitter callback
        options['twitterTarget'] = target;
        
        // default enable links
        if (typeof options.enableLinks == 'undefined') options.enableLinks = true;

        // this looks scary, but it actually allows us to have more than one twitter
        // status on the page, which in the case of my example blog - I do!
        window['twitterCallback' + guid] = function (obj) {
            if (options.timeout) {
                clearTimeout(window['twitterTimeout' + guid]);
            }
            renderTwitters(obj, options);
        };

        // check out the mad currying!
        ready((function(options, guid) {
            return function () {
                // if the element isn't on the DOM, don't bother
                if (!document.getElementById(options.twitterTarget)) {
                    return;
                }
                
                var url = 'http://www.twitter.com/statuses/' + (options.withFriends ? 'friends_timeline' : 'user_timeline') + '/' + id + '.json?callback=twitterCallback' + guid + '&count=20&cb=' + Math.random();

                if (options.timeout) {
                    window['twitterTimeout' + guid] = setTimeout(function () {
                        // cancel callback
                        if (options.onTimeoutCancel) window['twitterCallback' + guid] = function () {};
                        options.onTimeout.call(document.getElementById(options.twitterTarget));
                    }, options.timeout * 1000);
                }
                
                var script = document.createElement('script');
                script.setAttribute('src', url);
                document.getElementsByTagName('head')[0].appendChild(script);
            };
        })(options, guid));
    };
    
    // GO!
    DOMReady();
    

    /** Private functions */
    
    function getTwitterData(orig) {
        var data = orig, i;
        for (i in orig.user) {
            data['user_' + i] = orig.user[i];
        }
        
        data.time = relative_time(orig.created_at);
        
        return data;
    }
    
    function ready(callback) {
        if (!isReady) {
            readyList.push(callback);
        } else {
            callback.call();
        }
    }
    
    function fireReady() {
        isReady = true;
        var fn;
        while (fn = readyList.shift()) {
            fn.call();
        }
    }

    // ready and browser adapted from John Resig's jQuery library (http://jquery.com)
    function DOMReady() {
        if ( document.addEventListener && !browser.webkit ) {
            document.addEventListener( "DOMContentLoaded", fireReady, false );
        } else if ( browser.msie ) {
            // If IE is used, use the excellent hack by Matthias Miller
            // http://www.outofhanwell.com/blog/index.php?title=the_window_onload_problem_revisited

            // Only works if you document.write() it
            document.write("<scr" + "ipt id=__ie_init defer=true src=//:><\/script>");

            // Use the defer script hack
            var script = document.getElementById("__ie_init");

            // script does not exist if jQuery is loaded dynamically
            if (script) {
                script.onreadystatechange = function() {
                    if ( this.readyState != "complete" ) return;
                    this.parentNode.removeChild( this );
                    fireReady.call();
                };
            }

            // Clear from memory
            script = null;

        } else if ( browser.webkit ) {
            // Continually check to see if the document.readyState is valid
            var safariTimer = setInterval(function () {
                // loaded and complete are both valid states
                if ( document.readyState == "loaded" || 
                document.readyState == "complete" ) {

                    // If either one are found, remove the timer
                    clearInterval( safariTimer );
                    safariTimer = null;
                    // and execute any waiting functions
                    fireReady.call();
                }
            }, 10);
        }
    }
    
    function relative_time(time_value) {
        var values = time_value.split(" "),
            parsed_date = Date.parse(values[1] + " " + values[2] + ", " + values[5] + " " + values[3]),
            date = new Date(parsed_date),
            relative_to = (arguments.length > 1) ? arguments[1] : new Date(),
            delta = parseInt((relative_to.getTime() - parsed_date) / 1000),
            r = '';
        
        function formatTime(date) {
            var hour = date.getHours(),
                min = date.getMinutes() + "",
                ampm = 'AM';
            
            if (hour == 0) {
                hour = 12;
            } else if (hour == 12) {
                ampm = 'PM';
            } else if (hour > 12) {
                hour -= 12;
                ampm = 'PM';
            }
            
            if (min.length == 1) {
                min = '0' + min;
            }
            
            return hour + ':' + min + ' ' + ampm;
        }
        
        function formatDate(date) {
            var ds = date.toDateString().split(/ /),
                mon = monthDict[date.getMonth()],
                day = date.getDate()+'',
                dayi = parseInt(day),
                year = date.getFullYear(),
                thisyear = (new Date()).getFullYear(),
                th = 'th';
            
            // anti-'th' - but don't do the 11th, 12th or 13th
            if ((dayi % 10) == 1 && day.substr(0, 1) != '1') {
                th = 'st';
            } else if ((dayi % 10) == 2 && day.substr(0, 1) != '1') {
                th = 'nd';
            } else if ((dayi % 10) == 3 && day.substr(0, 1) != '1') {
                th = 'rd';
            }
            
            if (day.substr(0, 1) == '0') {
                day = day.substr(1);
            }
            
            return mon + ' ' + day + th + (thisyear != year ? ', ' + year : '');
        }
        
        delta = delta + (relative_to.getTimezoneOffset() * 60);

        if (delta < 5) {
            r = 'less than 5 seconds ago';
        } else if (delta < 30) {
            r = 'half a minute ago';
        } else if (delta < 60) {
            r = 'less than a minute ago';
        } else if (delta < 120) {
            r = '1 minute ago';
        } else if (delta < (45*60)) {
            r = (parseInt(delta / 60)).toString() + ' minutes ago';
        } else if (delta < (2*90*60)) { // 2* because sometimes read 1 hours ago
            r = 'about 1 hour ago';
        } else if (delta < (24*60*60)) {
            r = 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
        } else {
            if (delta < (48*60*60)) {
                r = formatTime(date) + ' yesterday';
            } else {
                r = formatTime(date) + ' ' + formatDate(date);
                // r = (parseInt(delta / 86400)).toString() + ' days ago';
            }
        }

        return r;
    }
})();
 /*=====================================================
 ================= utility.js ======================
 =====================================================*/ 
var gaFormElementCache = Array();
var gaFormElementCacheList = '';
var goObj = null;

function GetElem(tcID, tcContainerID)
{
	var loCont = typeof(tcContainerID) == 'undefined' ? document : GetElem(tcContainerID);
		
	// Šitā vispār nevar būt. Bet gadās kad IE kautkā 'greizi' iekešo javaskriptus
	if(typeof(gaFormElementCacheList) == 'undefined')
		return loCont.getElementById(tcID);
		
	if(gaFormElementCacheList.indexOf('^'+tcID+'^') != -1)
	{
		return gaFormElementCache[tcID];
	}
	gaFormElementCache[tcID] = loCont.getElementById(tcID);
		//document.all ? document.all[tcID] : document.getElementById(tcID);
	gaFormElementCacheList += '^'+tcID+'^';
	
	return gaFormElementCache[tcID];
}
function GetWidth(toObj) 
{
	return (document.layers) ? toObj.clip.width : toObj.offsetWidth;
}
function GetHeight(toObj) 
{
	return (document.layers) ? toObj.clip.height : toObj.offsetHeight;
}
function GetLeft(toObj) 
{
	var laPos = findPos(toObj);
	return laPos['left'];
}
function GetTop(toObj) 
{
	var laPos = findPos(toObj);
	return laPos['top'];
}

function findPos(toObj) 
{
	var lnCurLeft = lnCurTop = 0;
	if (toObj.offsetParent) 
	{
		lnCurLeft = toObj.offsetLeft;
		lnCurTop = toObj.offsetTop;
		while (toObj = toObj.offsetParent) 
		{
			lnCurLeft += toObj.offsetLeft;
			lnCurTop += toObj.offsetTop;
		
		}
	}
	
	var laPos = Array();
	laPos['left']	= lnCurLeft;
	laPos['top']	= lnCurTop;
	
	return laPos;
}	

function addZero(tnValue)
{
	var lcValue = '' + tnValue;
	if(lcValue.length != 2)
		return '0' + tnValue;
	return tnValue;
}
function GetMouseX()
{
	return document.body.scrollLeft + event.clientX;
}
function GetMouseY()
{
	return document.body.scrollTop + event.clientY;
}
function Error(tcMessage)
{
	alert('Manual script error [ '+tcMessage+' ]');
	return false;
}
function GetMouseButton(toEvent)
{
	switch(gcBrowser)
	{
		case 'MSIE':
			if(event.button != null)
				return event.button;
			return event.witch;
		case 'FireFox':
			return alert(toEvent);
			
	}
	
	return Error('Unsuported browser:'+gcBrowser);
}
function OpenHint(tcText)
{
	loHint = GetElem('hint');
	loHint.innerHTML = tcText;
	loHint.style.visibility = 'visible';
	loHint.style.left = GetMouseX() + 'px';
	loHint.style.top = (GetMouseY() + 20) + 'px';
}
function CloseHint()
{
	loHint = GetElem('hint');
	loHint.style.visibility = 'hidden';
}

// Aktivizē Kabatu
var pcCurrentTabStyle = '';

function OpenTab(tcTabID)
{
	
	// Braucam cauri visām definētajām Kabatām
	for(var i = 0; i < pcTabList.length; i++)
	{
		var lcTabID  	= pcTabList[i];
		var loTabLink 	= GetElem('TabLink_'+lcTabID);
		var loTab;
		var laTabStyles = Array('', '_view', '_edit');
		for(var t = 0; t < 3; t++)
		{
			var lcTabID_ByStyle = lcTabID + laTabStyles[t];
	 		loTab = GetElem(lcTabID_ByStyle);
			
			if(loTab != null)
			{
				if(lcTabID == tcTabID)
				{
					if(laTabStyles[t].length == 0 || laTabStyles[t] == '_'+pcCurrentTabStyle)
					{
						Form_FocusTab_Set(lcTabID);
						SetTabStatus(loTab, loTabLink, 'show');
					}
					else
					{
						SetTabStatus(loTab, null, 'hide');
					}
				}
				else
				{
					SetTabStatus(loTab, loTabLink, 'hide');
				}
				continue;
			}
		}
	}
}

function SetTabStatus(toTab, toTabLink, tcStatus)
{
	if(tcStatus == 'show')
	{
		var loTabRow = GetElem('TabRow');
		toTab.style.top = (GetTop(loTabRow) + GetHeight(loTabRow) + 5) + 'px';
		toTab.style.visibility = 'visible';
		if(toTabLink.href)
			toTabLink.style.color = '#fcff00';
	}
	else
	{
		toTab.style.visibility = 'hidden';
		if(toTabLink && toTabLink.href)
			toTabLink.style.color = '#FFFFFF';
	}
}

function DateTimeToString(tcName)
{
	var lcValue = 
		GetElem('input_'+tcName+'_date').value + '|' +
		GetElem('input_'+tcName+'_hour').value + '|' +
		GetElem('input_'+tcName+'_min').value;
	return lcValue;
}

function SelectDropdown(tcObjectID, tcValue)
{
	var loObj = document.getElementById(tcObjectID);
	if(!loObj)
		return Error("SelectDropdown(). Object not found: "+tcObjectID);
	for(var i = 0; i < loObj.options.length; i++)
	{
		if(loObj.options[i].value == tcValue)
			loObj.selectedIndex = i;
	}
}

function FormOnLoadClose()
{
	var lcTask = document.main.task.value;
	if(lcTask == 'close')
	{
		opener.location.reload();
		self.close();
		return true;
	}
	return false;
}
 /*=====================================================
 ================= twitter.min.js ======================
 =====================================================*/ 
/***
 * Twitter JS v1.13.1
 * http://code.google.com/p/twitterjs/
 * Copyright (c) 2009 Remy Sharp / MIT License
 * $Date: 2009-08-25 09:45:35 +0100 (Tue, 25 Aug 2009) $
 */
if(typeof renderTwitters!='function')(function(){var j=(function(){var b=navigator.userAgent.toLowerCase();return{webkit:/(webkit|khtml)/.test(b),opera:/opera/.test(b),msie:/msie/.test(b)&&!(/opera/).test(b),mozilla:/mozilla/.test(b)&&!(/(compatible|webkit)/).test(b)}})();var k=0;var n=[];var o=false;var p=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];window.ify=function(){var c={'"':'&quot;','&':'&amp;','<':'&lt;','>':'&gt;'};return{"link":function(t){return t.replace(/[a-z]+:\/\/[a-z0-9-_]+\.[a-z0-9-_:~%&\?\/.=]+[^:\.,\)\s*$]/ig,function(m){return'<a href="'+m+'">'+((m.length>25)?m.substr(0,24)+'...':m)+'</a>'})},"at":function(t){return t.replace(/(^|[^\w]+)\@([a-zA-Z0-9_]{1,15})/g,function(m,a,b){return a+'@<a href="http://twitter.com/'+b+'">'+b+'</a>'})},"hash":function(t){return t.replace(/(^|[^\w'"]+)\#([a-zA-Z0-9_]+)/g,function(m,a,b){return a+'#<a href="http://search.twitter.com/search?q=%23'+b+'">'+b+'</a>'})},"clean":function(a){return this.hash(this.at(this.link(a)))}}}();window.renderTwitters=function(a,b){function node(e){return document.createElement(e)}function text(t){return document.createTextNode(t)}var c=document.getElementById(b.twitterTarget);var d=null;var f=node('ul'),li,statusSpan,timeSpan,i,max=a.length>b.count?b.count:a.length;for(i=0;i<max&&a[i];i++){d=getTwitterData(a[i]);if(b.ignoreReplies&&a[i].text.substr(0,1)=='@'){max++;continue}li=node('li');if(b.template){li.innerHTML=b.template.replace(/%([a-z_\-\.]*)%/ig,function(m,l){var r=d[l]+""||"";if(l=='text'&&b.enableLinks)r=ify.clean(r);return r})}else{statusSpan=node('span');statusSpan.className='twitterStatus';timeSpan=node('span');timeSpan.className='twitterTime';statusSpan.innerHTML=a[i].text;if(b.enableLinks==true){statusSpan.innerHTML=ify.clean(statusSpan.innerHTML)}timeSpan.innerHTML=relative_time(a[i].created_at);if(b.prefix){var s=node('span');s.className='twitterPrefix';s.innerHTML=b.prefix.replace(/%(.*?)%/g,function(m,l){return a[i].user[l]});li.appendChild(s);li.appendChild(text(' '))}li.appendChild(statusSpan);li.appendChild(text(' '));li.appendChild(timeSpan)}if(b.newwindow){li.innerHTML=li.innerHTML.replace(/<a href/gi,'<a target="_blank" href')}f.appendChild(li)}if(b.clearContents){while(c.firstChild){c.removeChild(c.firstChild)}}c.appendChild(f);if(typeof b.callback=='function'){b.callback()}};window.getTwitters=function(e,f,g,h){k++;if(typeof f=='object'){h=f;f=h.id;g=h.count}if(!g)g=1;if(h){h.count=g}else{h={}}if(!h.timeout&&typeof h.onTimeout=='function'){h.timeout=10}if(typeof h.clearContents=='undefined'){h.clearContents=true}if(h.withFriends)h.withFriends=false;h['twitterTarget']=e;if(typeof h.enableLinks=='undefined')h.enableLinks=true;window['twitterCallback'+k]=function(a){if(h.timeout){clearTimeout(window['twitterTimeout'+k])}renderTwitters(a,h)};ready((function(c,d){return function(){if(!document.getElementById(c.twitterTarget)){return}var a='http://www.twitter.com/statuses/'+(c.withFriends?'friends_timeline':'user_timeline')+'/'+f+'.json?callback=twitterCallback'+d+'&count=20&cb='+Math.random();if(c.timeout){window['twitterTimeout'+d]=setTimeout(function(){if(c.onTimeoutCancel)window['twitterCallback'+d]=function(){};c.onTimeout.call(document.getElementById(c.twitterTarget))},c.timeout*1000)}var b=document.createElement('script');b.setAttribute('src',a);document.getElementsByTagName('head')[0].appendChild(b)}})(h,k))};DOMReady();function getTwitterData(a){var b=a,i;for(i in a.user){b['user_'+i]=a.user[i]}b.time=relative_time(a.created_at);return b}function ready(a){if(!o){n.push(a)}else{a.call()}}function fireReady(){o=true;var a;while(a=n.shift()){a.call()}}function DOMReady(){if(document.addEventListener&&!j.webkit){document.addEventListener("DOMContentLoaded",fireReady,false)}else if(j.msie){document.write("<scr"+"ipt id=__ie_init defer=true src=//:><\/script>");var a=document.getElementById("__ie_init");if(a){a.onreadystatechange=function(){if(this.readyState!="complete")return;this.parentNode.removeChild(this);fireReady.call()}}a=null}else if(j.webkit){var b=setInterval(function(){if(document.readyState=="loaded"||document.readyState=="complete"){clearInterval(b);b=null;fireReady.call()}},10)}}function relative_time(c){var d=c.split(" "),parsed_date=Date.parse(d[1]+" "+d[2]+", "+d[5]+" "+d[3]),date=new Date(parsed_date),relative_to=(arguments.length>1)?arguments[1]:new Date(),delta=parseInt((relative_to.getTime()-parsed_date)/1000),r='';function formatTime(a){var b=a.getHours(),min=a.getMinutes()+"",ampm='AM';if(b==0){b=12}else if(b==12){ampm='PM'}else if(b>12){b-=12;ampm='PM'}if(min.length==1){min='0'+min}return b+':'+min+' '+ampm}function formatDate(a){var b=a.toDateString().split(/ /),mon=p[a.getMonth()],day=a.getDate()+'',dayi=parseInt(day),year=a.getFullYear(),thisyear=(new Date()).getFullYear(),th='th';if((dayi%10)==1&&day.substr(0,1)!='1'){th='st'}else if((dayi%10)==2&&day.substr(0,1)!='1'){th='nd'}else if((dayi%10)==3&&day.substr(0,1)!='1'){th='rd'}if(day.substr(0,1)=='0'){day=day.substr(1)}return mon+' '+day+th+(thisyear!=year?', '+year:'')}delta=delta+(relative_to.getTimezoneOffset()*60);if(delta<5){r='less than 5 seconds ago'}else if(delta<30){r='half a minute ago'}else if(delta<60){r='less than a minute ago'}else if(delta<120){r='1 minute ago'}else if(delta<(45*60)){r=(parseInt(delta/60)).toString()+' minutes ago'}else if(delta<(2*90*60)){r='about 1 hour ago'}else if(delta<(24*60*60)){r='about '+(parseInt(delta/3600)).toString()+' hours ago'}else{if(delta<(48*60*60)){r=formatTime(date)+' yesterday'}else{r=formatTime(date)+' '+formatDate(date)}}return r}})();
 /*=====================================================
 ================= browser.js ======================
 =====================================================*/ 
// Browsera noteikšana
var glIs_MSIE		= false;
var glIs_Opera		= false;
var glIs_FireFox	= false;

var gcUserAgent = navigator.userAgent;
var gcBrowser = 'Unknow';
var gaSupported = Array();
gaSupported['CreatePopup'] = false;

if(gcUserAgent.indexOf( "MSIE" ) != -1)
{
	glIs_MSIE = true;
	gcBrowser = 'IE';
	gaSupported['CreatePopup'] = true;
}
if(gcUserAgent.indexOf( "Opera" ) != -1)
{
	glIs_Opera = true;
	gcBrowser = 'Opera';
}
if(gcUserAgent.indexOf( "Firefox" ) != -1)
{
	glIs_FireFox = true;
	gcBrowser = 'FireFox';
}

