// Function checks if JavaScript textual field is blank.
// @param  obj    JS object textual field (Input or TextArea)
// @param  msg    optional message which may be shown if the field is blank
// @return true if check successful
function isNotEmpty(obj, msg) 
{
    if ( obj && obj.value.match(/^\s*$/g) )
    {
        if ( msg && msg != '')
        {
            alert(msg)
            obj.focus();
        }
        return false;
    }
    return true;
}


function checkEmail(email, message)
{
   if (isNotEmpty(email) && !isEmailCorrect(email.value))
   {
    if (message && message != '')
    {
        alert(message);
        email.focus();
    }
    return false;
   }
   return true;
}

/**
 * @param email email string
 */
function isEmailCorrect(email)
{
    return email.match(/^[-!#$%&\'*+\\.\/0-9=?a-zA-Z^_`{|}~]+@([a-zA-Z0-9\._-]+\.)+([0-9a-zA-Z]){2,4}$/) != null;
}
  
// Select <select> option by value
function select_option(select_obj, value)
{
    for (i = 0; i < select_obj.options.length; i++)
    {
        if (select_obj.options[i].value == value)
        {
            select_obj.options[i].selected = true;
        }
    }
}

function checkState(state_obj, country_obj)
{
    if (state_obj.selectedIndex != 0)
    {
        country_obj.selectedIndex = 0;
    }
}

function checkCountry(state_obj, country_obj)
{
    if (country_obj.selectedIndex != 0)
    {
        state_obj.selectedIndex = 0;
    }
}

function openWindow(name,url,width,height)
{
    var popupWin = window.open(url,name,'width='+width+',height='+height+',location=no,resizable=yes,scrollbars=yes');
	//alert(popupWin.document.onload);
	popupWin.focus();
	//alert(popupWin.document.onload);
}

// Function trims space characters of specified field value
function trim(obj)
{
    obj.value = trimValue(obj.value);
}

function trimValue( val )
{
	val = val.replace(/^\s*/, "");
	return val.replace(/\s+$/, "");	
}

function isSpecified(element_obj) {
		if (element_obj) {
			//If this element is a file - we should check if there is file option present and if it is - what is the choice - to keep, replace or delete a file
			if ((!element_obj[0]) && element_obj.form.elements[element_obj.name + "_fileOption"] != null)
			{
				value = getRadioElementValue(element_obj.form.elements[element_obj.name + "_fileOption"]);
				if (value=="keep")
				{
					return true; //we assume that file options only appear if file is uploaded ok
				}
				else if (value=="replace")
				{
					return element_obj.form.elements[element_obj.name + "_new"] == null
						? false
						: trim(element_obj.form.elements[element_obj.name + "_new"]) != '';
				}
				else
				{
					return false;
				}
			}
			if ((element_obj[0]) && (element_obj[0].type == 'radio')) {
				var checked = false;
				for (k = 0; k < element_obj.length; k++) {
					checked = checked || element_obj[k].checked;
				}
				return checked;
			}
			else if (element_obj.type == 'select-one' || element_obj.type == 'select-multiple')
			{
				var value = getSelectedValue(element_obj);
				return (value.length > 0);
			}
			else 
			{
				trim(element_obj);
				return (element_obj.value.length > 0);
			}
		}
		return true;
	}

	function focusOn(element)
	{
		if ((element[0]) && (element[0].type == 'radio'))
		{
			element[0].focus();
		}
		else 
		{
			element.focus();
		}
	}

	function checkRequiredElements(form, reqEl) {
		var message = "Please specify values for the following fields:\r\n";
		var elementToFocus = null;

		for (var i = 0; i < reqEl.length; i++) {
			var element = form.elements[reqEl[i][0]];
			if (isSpecified(element) == false) {
				if (elementToFocus == null) {
					elementToFocus = element;
				} else {
					message += ', ';
				}
				message += reqEl[i][1];
			}
		}
		if (elementToFocus != null) {
			alert(message);
			if (elementToFocus.type != 'hidden') {
				focusOn(elementToFocus);
			}
			return false;
		}
		return true;
	}

	function getSelectedRadio(radioCol)
	{
		var i;
		for (i = 0; i < radioCol.length; i++)
		{	
			if (radioCol[i].checked)
			{
				return radioCol[i];
			}
		}
		return null;
	}

	function getSelectedValue(selectObj)
	{
		if (selectObj.selectedIndex >= 0)
		{
			return selectObj.options[selectObj.selectedIndex].value;
		} else {
			return null;
		}
	}

	function getRadioElementValue(radioCol)
	{
		var i;
		
		if (radioCol.selectedIndex == null)
		{
			for (i = 0; i < radioCol.length; i++)
			{	
				if (radioCol[i].checked)
				{
					return radioCol[i].value;
				}
			}
		}
		else
		{
			return getSelectedValue(radioCol);
		}
	}

	function checkRequiredInfo(form, infoArray, infoEl)
	{
		var elementToFocus = null;
		var n = 0;
		var i = 0;
		outer:
		for (i = 0; i < infoArray.length; i++)
		{
			if (infoArray[i][0] == infoEl)
			{
				var j;
				for (j = 1; j < infoArray[i][1].length; j++)
				{
					var element = form.elements[infoArray[i][1][j]];
					if (isSpecified(element) == false) {
						elementToFocus = element;
						n = i;
						break outer;
					}
				}
			}
		}
		if (elementToFocus != null)
		{
			alert(infoArray[n][1][0]);
			focusOn(elementToFocus);
			return false;
		} else
			return true;
	}

	function setRequired(form, elementName, control, starImgUrl, emptyImgUrl) {
    
        if (control=="Select") //Select control
        {
            col = form.elements[elementName].options;
	    	for (i = 0; i < col.length; i++) {
		    	j = 0;
			    //alert(col[i].selected);
                //alert(elementName + col[i].value + j);
    			while((depEl = document.images[elementName + col[i].value + j]) != null)
	    		{
		    		//alert(depEl + ' - ' + elementName + col[i].value + j);
			    	depEl.src = col[i].selected ? starImgUrl : emptyImgUrl;
				    j++;
    			}
	    	}
        } 
        else // Radio buttons control
        {
    		col = form.elements[elementName];
	    	for (i = 0; i < col.length; i++) {
		    	j = 0;
			    //alert(col[i].checked);
    			while((depEl = document.images[elementName + col[i].value + j]) != null)
	    		{
		    		//alert(depEl + ' - ' + elementName + col[i].value + j);
			    	depEl.src = col[i].checked ? starImgUrl : emptyImgUrl;
				    j++;
    			}
	    	}
		}
	}
    function findPosX(obj)
    {
        var curleft = 0;
        if (obj.offsetParent)
        {
            while (obj.offsetParent)
            {
                curleft += obj.offsetLeft
                obj = obj.offsetParent;
            }
        }
        else if (obj.x)
            curleft += obj.x;
        return curleft;
    }
    function findPosY(obj)
    {
        var curtop = 0;
        if (obj.offsetParent)
        {
            while (obj.offsetParent)
            {
                curtop += obj.offsetTop
                obj = obj.offsetParent;
            }
        }
        else if (obj.y)
            curtop += obj.y;
        return curtop;
    }
    function getInsideWindowWidth( ) {
        if (window.innerWidth) {
            return window.innerWidth;
        } else if( document.documentElement && ( document.documentElement.clientWidth ) ) {
          //IE 6+ in 'standards compliant mode'
          return document.documentElement.clientWidth;
        } else if (document.body && document.body.clientWidth) {
            return document.body.clientWidth;
        } else if (document.body && document.body.parentElement) {
            return document.body.parentElement.clientWidth;
        }
        return 0;
    }
    
    function showScreen(pict,width,height,orig){
        var zoom_view = document.getElementById("zoom_view");
        var zoom_screen = document.getElementById("zoom_screen");
        var clicked_pict = document.getElementById(orig);
        
        zoom_view.style.display = "none";
        zoom_screen.width = width;
        zoom_screen.height = height;
        zoom_screen.src = "img/pixel.gif";
        zoom_screen.src = pict;
        
        var delta_y = (height - clicked_pict.height)/2;
        var y_pos = findPosY(clicked_pict) - delta_y;
        if(y_pos < 80) y_pos = 80;
        zoom_view.style.top = y_pos;

        var delta_x = (width - clicked_pict.width)/2;
        var x_pos = findPosX(clicked_pict) - delta_x;
        var correction = (x_pos + width - getInsideWindowWidth() + 38);
        if(correction < 0) correction = 0;
        x_pos = x_pos - correction;
        if(x_pos < 20) x_pos = 20;
        zoom_view.style.left = x_pos;

        zoom_view.style.display = "inline";
    }

    function hideScreen(){
        var zoom_view = document.getElementById("zoom_view");
        zoom_view.style.display = "none";
    }

	function init()
	{
	}

    /**
     * Scrolls the window, so that the specified element is fully visible. 
     */
    function scrollToElementIfNeeded(element)
    {
        var elemTop = 0;
        var elemHeight = element.clientHeight;

        while(element != null)
        {
            elemTop += element.offsetTop;
            element = element.offsetParent;
        }

        var elemBottom = elemTop + elemHeight;

        var viewPort = getViewPortHeight();

        if (elemBottom > getBodyScrollTop() + viewPort)
            window.scrollTo(0, elemBottom - getViewPortHeight());
    }

    /**
     * http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/ 
     */
    function getViewPortHeight()
    {
        var viewportheight;

        // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
        if (typeof window.innerHeight != 'undefined')
            viewportheight = window.innerHeight;

        // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
        else if (typeof document.documentElement != 'undefined'
         && typeof document.documentElement.clientHeight !=
         'undefined' && document.documentElement.clientHeight != 0)
            viewportheight = document.documentElement.clientHeight;
        // older versions of IE
        else
           viewportheight = document.getElementsByTagName('body')[0].clientHeight;

        return viewportheight;
    }

    /**
     * http://www.cyberguru.ru/web/html/javascript-samples-page29.html
     */
    function getBodyScrollTop()
    {
        return self.pageYOffset ||
               (document.documentElement && document.documentElement.scrollTop) ||
               (document.body && document.body.scrollTop);
    }
