﻿
/**
 * Framework
 *
 * @copyright Copyright (c) 2009, inaction.lt
 * @author    Benas Valančius <benas@inaction.lt>
 * @package   Framework
 *
 * $Id: functions.js 209 2009-02-09 19:51:08Z noen $
 */

/**
 * document.getElementById() shortcut
 *
 * @param string itemId
 *
 * @return object
 */
function $$(itemId)
{
    if(!itemId) return null;
    var returnObj = document.getElementById(itemId);
    if(!returnObj && document.all) returnObj = document.all[itemId];
    return returnObj;
}

/**
 * Language compiler
 *
 * @param string langId - language id
 * @param string module - module name
 *
 * @return string
 */
function _(langId, module)
{
    if(module != undefined && __M[module +'_'+ langId] != undefined)
        return __M[module +'_'+ langId];

    if(__[langId] != undefined)
        return __[langId];

    return '*'+ langId +'*';
}

/**
 * Find object position
 *
 * @param object obj
 *
 * @return array
 */
function findPos(obj)
{
    var curleft = curtop = 0;
    if (obj.offsetParent)
    {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop
        while (obj = obj.offsetParent)
        {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
    }
    return [curleft,curtop];
}

/**
 * Set dhtml obejct opacity
 *
 * @param object  obj
 * @param integer opacity [1-100]
 */
function setOpacity(obj, opacity)
{
    obj.style.filter = "alpha(opacity:" + opacity + ")";
    obj.style.KHTMLOpacity = opacity / 100;
    obj.style.MozOpacity = opacity / 100;
    obj.style.opacity = opacity / 100;
}

/**
 * encodeHtml
 *
 * @param string text
 *
 * @return string
 */
function encodeHtml(text)
{
    text = text.replace(/&/g, "&amp;");
    text = text.replace(/"/g, "&quot;");
    text = text.replace(/'/g, "&#039;");
    text = text.replace(/</g, "&lt;");
    text = text.replace(/>/g, "&gt;");
    return text;
}

/**
 * Add slashes
 *
 * @param string string
 */
function add_slashes(string)
{
    string = string.replace(/\\/g, "\\\\"); // \ => \\
    string = string.replace(/\'/g, "\\'");  // ' => \'
    return string;
}

/**
 * Get all form item values
 *
 * @param string form_name
 *
 * @return array
 */
function getFormElements(form_name)
{
    var outup = {};

    eval('var el = document.'+form_name+'.elements;');
    eval('var totalElements = el.length;');

    for(i=0; i<totalElements; i++)
    {
        if(el[i].name != undefined)
        {
            var value = null;

            switch (el[i].type)
            {
                case 'text':
                case 'submit':
                case 'hidden':
                case 'password':
                    value = el[i].value;
                    break;
                case 'radio':
                    if(el[i].checked)
                        value = el[i].value;
                    break;
                case 'select-one':
                    value = el[i].value;
                    break;
                case 'select-multiple':
                    var nr = 0;
                    var multiple_element_lenght = el[i].options.length;
                    value = new Array();
                    for(n=0; n<multiple_element_lenght; n++)
                    {
                        if(el[i].options[n].selected)
                        {
                            value[nr] = el[i].options[n].value;
                            nr++;
                        }
                    }
                    break;
                case 'checkbox':
                    if(el[i].checked)
                        value = el[i].value;
                    break;
                case 'textarea':
                    value = el[i].value;
                    break;
                default:
                    //outup += 'type: ' + element_type + ", name: " + el[i].name + " | unknown &";
            }
            
            if(value != null)
            {
                if(el[i].name.substr(-2) == '[]')
                {
                    var name = el[i].name.substr(0, el[i].name.length-2);

                    if(outup[name] == undefined)
                        outup[name] = new Array();

                    outup[name].push(value);
                }
                else
                {
                    outup[el[i].name] = value;
                }
            }
        }
    }
    return outup;
}

/**
 * elemento display keitimas
 */
function display(item_id)
{
    $$(item_id).style.display = ($$(item_id).style.display == 'none') ? '' : 'none';
}

/**
 * Draggable
 */
var dragObj = new Object();

function dragStart(e, id)
{
    var x, y;

    e = e || window.event;
    
    if (id)
    {
        dragObj.elNode = $$(id);
    }
    else
    {
        if(e.target)
            dragObj.elNode = e.target;
        else if(e.srcElement)
            dragObj.elNode = e.srcElement;
        else
            alert('error:unsupported browser');

        if (dragObj.elNode.nodeType == 3)
            dragObj.elNode = dragObj.elNode.parentNode;
    }

    if (window.scrollX) 
    {
        x = e.clientX + window.scrollX;
        y = e.clientY + window.scrollY;
    }
    else
    {
        x = e.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
        y = e.clientY + document.documentElement.scrollTop + document.body.scrollTop;
    }

    dragObj.cursorStartX = x;
    dragObj.cursorStartY = y;
    dragObj.elStartLeft  = parseInt(dragObj.elNode.style.left, 10);
    dragObj.elStartTop   = parseInt(dragObj.elNode.style.top,  10);

    if(isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0;
    if(isNaN(dragObj.elStartTop))  dragObj.elStartTop  = 0;

    dragObj.elNode.style.zIndex = ++dragObj.zIndex;

    $(document).bind('mousemove', dragGo);
    $(document).bind('mouseup', dragStop);
    e.stopPropagation();
}

function dragGo(e)
{
    var x, y;

    e = e || window.event;

    if (window.scrollX) 
    {
        x = e.clientX + window.scrollX;
        y = e.clientY + window.scrollY;
    }
    else
    {
        x = e.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
        y = e.clientY + document.documentElement.scrollTop + document.body.scrollTop;
    }

    var blockX = dragObj.elStartLeft + x - dragObj.cursorStartX;
    var blockY = dragObj.elStartTop  + y - dragObj.cursorStartY;

    if(blockX < 1) blockX = 1;
    if(blockY < 1) blockY = 1;

    if(blockX > document.documentElement.clientWidth - dragObj.elNode.offsetWidth)   blockX = document.documentElement.clientWidth - dragObj.elNode.offsetWidth - 1;
    if(blockY > document.documentElement.clientHeight - dragObj.elNode.offsetHeight) blockY = document.documentElement.clientHeight - dragObj.elNode.offsetHeight - 1;

    dragObj.elNode.style.left = blockX + 'px';
    dragObj.elNode.style.top  = blockY + 'px';

    e.stopPropagation();
    return false;
}

function dragStop(e)
{
    $(document).unbind('mousemove', dragGo);
    $(document).unbind('mouseup', dragStop);
    e.stopPropagation();
    return false;
}

var form = {};

/**
 * Check email validation
 *
 * @param string email - email address
 *
 * @return bool
 */
form.checkemail = function(email)
{
    var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    if (filter.test(email))
        return true;

    return false;
}

/**
 * Check date validation
 *
 * @param string Y - Year YYYY
 * @param string M - Mounth MM
 * @param string D - Day DD
 *
 * @return bool
 */
form.checkDate = function(Y, M, D)
{
    //var Y = parseInt(Y);
    //var M = parseInt(M);
    //var D = parseInt(D);
    var Y = Y - 0;
    var M = M - 0;
    var D = D - 0;

    if(!(Y >= 1000 && Y <= 3000))
        return false;

    if(!(M >= 1 && M <= 12))
        return false;

    var dayCount = {1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31};

    if(Y % 4 == 0)
        dayCount[2] += 1;

    if(!(D >= 1 && D <= dayCount[M]))
        return false;

    return true;
}

/**
 * Make background color animation
 *
 * @param string id - Element ID
 */
function tempHighlight(id)
{
    $('#'+ id).css('background','#ffff99');
    $('#'+ id).stop();
    $('#'+ id).animate({backgroundColor:'#ffffff'}, 1500);
}

/**
 * Debuger
 *
 * @param mixed obj
 */
function DUMP(obj)
{
    // TODO: naudoti ne alert o popup
    var temp = '';
    for(var x in obj)
    {
        temp += x + ": " + obj[x] + "\n";
    }
    alert(temp);
}

/** jQuery plugins */

/**
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 * Modified by Ben XO to expose getRGB and getColor through jQuery
 */
(function(jQuery){
    jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){ jQuery.fx.step[attr] = function(fx){ if(fx.state == 0){ fx.start = getColor( fx.elem, attr ); fx.end = getRGB( fx.end ); } fx.elem.style[attr] = "rgb(" + [ Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0), Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0), Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0) ].join(",") + ")"; } });
    function getRGB(color) { var result; if(color && color.constructor == Array && color.length == 3) return color; if(result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color)) return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])]; if(result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color)) return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55]; if(result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color)) return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)]; if(result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color)) return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)]; return colors[jQuery.trim(color).toLowerCase()]; }
    function getColor(elem, attr) { var color; do { color = jQuery.curCSS(elem, attr); if(color != '' && color != 'transparent' || jQuery.nodeName(elem, "body")) break; attr = "backgroundColor"; } while (elem = elem.parentNode); return getRGB(color); };
})(jQuery);
