/**
 * Remove image and set empty string in database.
 * Ajax request
 * params @def
 * return null;
*/
function generateSecureCode(){
	var secureImg = document.getElementById("secureImg");
	if(secureImg){
		secureImg.src = baseURL + "/public/php_lib/captcha/captcha.php" + "?val=" + Math.floor(Math.random()*1000000);
	}
}

String.prototype.trim = function() {
	a = this.replace(/^\s+/, '');
	return a.replace(/\s+$/, '');
};

Array.prototype.inArray = function (value) {
// Returns true if the passed value is found in the
// array. Returns false if it is not.
	var i;
	for (i=0; i < this.length; i++) {
		// Matches identical (===), not just similar (==).
		if (this[i] === value) 
			return true;
	}
	return false;
};

function RemoveDuplicates(arr){
	if(isArray(arr)){
		arr.sort();
		returnArray = true;
	} else {
		returnArray = false;
		arr.trim();
		arr = arr.split(" ");
		arr.sort();
	}
	var result=new Array();
	var lastValue="";
	for (var i=0; i<arr.length; i++){
		var curValue=arr[i];
		if (curValue != lastValue){
			result[result.length] = curValue;
		}
		lastValue = curValue;
	}
	if(!returnArray){
		var newResult = "";
		for (var a=0; a < result.length; a++){
			newResult += result[a] + " ";
		}
		newResult.trim();
		result = newResult;
	}
	return result;
}

function isArray() {
	if (typeof arguments[0] == 'object') { 
		var criterion = arguments[0].constructor.toString().match(/array/i); 
		return (criterion != null); 
	}
	return false;
}

function isset(v) {
	return((typeof(v)=='undefined' || v.length==0) ? false : true);
}

function getBasePath(){
        var tmpChildNodes = document.documentElement.firstChild.childNodes;
            var path = "";
            for(var ii = 0; ii < tmpChildNodes.length; ii++){
                        var elem = tmpChildNodes[ii];
                        if(elem.tagName == "BASE"){
                                path = elem.href;
                                break;
                        }
            }
            return path;
}

//added for removing specification and image from procurement and products
function removeSpec(id, doc_id, ref_id, type){
        
        if(!id || !doc_id || !ref_id){
                return false;
        }
        document.getElementById(ref_id).style.visibility = 'hidden';
        if(type == 1) //procurement specification
        	part_url = 'remspec=1&rfqid=' + id;
        else if(type == 2) //product specification
        	part_url = 'remdoc=1&docid=' + id;
        else if(type == 3) //product image
        	part_url = 'remimg=1&imgid=' + id;
        else if(type == 4) //mark product image
            part_url = 'remimg=2&imgid=' + id;
        else if(type == 5) //mark product doc
            part_url = 'remdoc=2&docid=' + id;
        else if(type == 6) //mark product doc
            part_url = 'remextraimg=1&ppid=' + id;
        else if(type == 7) //product release doc
            part_url = 'remnewsdoc=1&newsid=' + id;
        	
        var url = baseURL+'/public/php_lib/removeimgdoc.php?' + part_url;
		var req = getXMLHTTP();
		req.open('get', url, false); //third parameter is set to false here
		req.send(null);
		response = req.responseText;
		
		if(response == "true"){
			document.getElementById(doc_id).style.display = 'none';
        }else{
			alert("Removing error");
        }
}
function removeImages(id, doc_id, type){
        document.getElementById('image_show_'+doc_id).style.display = 'none';
        if(!id || !doc_id ){
                return false;
        }
        if (type)
            part_url = 'remnewsimg=1&id=' + id;
        else
            part_url = 'remextraimg=1&ppid=' + id;
            
        var url = baseURL+'/php_lib/removeimgdoc.php?' + part_url;
        
        var req = getXMLHTTP();
        req.open('get', url, false); //third parameter is set to false here
        req.send(null);
        response = req.responseText;
        
        if(response == "true"){
            document.getElementById('image_add_'+doc_id).style.display = 'block';
        }else{
            alert("Removing error");
        }
}

function URLEncode(value)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = value;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
}

function delData(url, pid)
{
   if (url.length==0) {
       document.getElementById("txtResult").innerHTML="";
       return;
   }
   url= url+"?"+pid;
   var req = getXMLHTTP();
   req.open('get', url, false); //third parameter is set to false here
   req.send(null);
   document.location.reload(true);

}


function showSubmenu(id){
    document.getElementById("submenu"+id).style.display = 'block';
}
function hideSubmenu(id){
    document.getElementById("submenu"+id).style.display = 'none';
}

//end of added

// PLEASE DO NOT REMOVE THIS. THANKS
// FIND GREATE JAVASCRIPT CODES AT http://www.wallpaperama.com
function toggleLayer( whichLayer ) {
var elem, vis;
if( document.getElementById ) // this is the way the standards work
elem = document.getElementById( whichLayer );
else if( document.all ) // this is the way old msie versions work
elem = document.all[whichLayer];
else if( document.layers ) // this is the way nn4 works
elem = document.layers[whichLayer];
vis = elem.style;
// if the style.display value is blank we try to figure it out here
if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
vis.display = (vis.display==''||vis.display=='block')?'none':'block';
}

function setClientTime(form){ 
    now = new Date(); 
    form.clientTime.value = now.toString(); 
    return true; 
} 

function buttonHoverOut(id, the_class){
    document.getElementById(id).className = the_class;
    return;
}

//FUNCTIONS FOR FORM VALIDATION
function doAdminValidation(myform, url)
{
    var data = {};var ids = {};
    $("input").each(function()
    {
        if ($(this).attr('type') != 'file')
        {
            data[$(this).attr('name')] = $(this).val();
            ids[$(this).attr('name')] = $(this).attr('id');
        }
    });
    $('select').each(function()
    {
        data[$(this).attr('id')] = $(this).val();
        ids[$(this).attr('id')] = $(this).attr('id');
    });
    $('textarea').each(function()
    {
        data[$(this).attr('name')] = $(this).val();
        ids[$(this).attr('name')] = $(this).attr('id');
    });
    $.post(url,data,function(resp)
    {
        if($(resp).length == 0){
            $('#'+myform).submit();}
        else
        {
            for(id in ids)
            {
                //alert($("#sp_cat").parent().attr('class'));                    
                //$("#"+id).parent().find('.error').remove();
                //$("#"+id).parent().append(getErrorHtml(resp[id], id));
                  $("#error-"+id).html(getErrorHtml(resp[id], id));
                //$('#all').append(getErrorHtml(resp[id], id));
            }
            return false;
         }
    },'json');
}
function getErrorHtml(formErrors , id)
{
    //var o = '<span id="error-'+id+'" class="error">';
    var o = '';
    for(errorKey in formErrors)
    {
        o += formErrors[errorKey];
    }
    //o += '</span>';
    return o;
}
function selected_radio(){
    $('.row label').click(function(e) {
        var label_for = $(this).attr('for');//alert(radio_id);
        if(label_for == "video-url"){
                $("#show_url").show();
                $("#show_embed").hide();
        }
        if(label_for == "video-embed"){
                $("#show_url").hide();
                $("#show_embed").show();
        }

    });
}
//end form validation
