$(document).ready(function(){
    pridatTargetBlank('new_window');
    nastavitAkceProGalerie('onclickChangeDetail');
    putSuggest('search_input');
    
    // menu
    var menu = document.getElementById('menu');
    var elms = getElementsByClassName('menuLink',menu);
    for (var i = 0; i < elms.length; i++) {
        var nextSiblingElm = elms[i].nextSibling;
        if (nextSiblingElm && nextSiblingElm.tagName == 'UL') {
            elms[i].href = 'javascript: void(0)'; 
            elms[i].style.borderWidth = '20px';
        }
    }
    
    $('#menu ul').hide();
    $('#menu li a').click(
        function() {
                $(this).next().slideToggle('fast');
        }
    );
    
    if (document.getElementById('overlay_mask')) {
        var main_wrap_elm = document.getElementsByTagName('body')[0];
        var new_height = main_wrap_elm.offsetHeight;
        var new_width = main_wrap_elm.offsetWidth;
        document.getElementById('overlay_mask').style.height = new_height+'px';
        document.getElementById('o_content').style.left = ((new_width - 731) / 2)+'px'; 
    }
    
    /* Highlits selected link parrents */    
    if (higlight_menu_id) {
        $('#'+higlight_menu_id).parents().show();
        $('#'+higlight_menu_id).addClass('selected');
    }
});

$.fn.wait = function(time, type) {
    time = time || 500;
    type = type || "fx";
    return this.queue(type, function() {
        var self = this;
        setTimeout(function() {
            $(self).dequeue();
        }, time);
    });
};

function getElementsByClassName(classname, node) {
    if(!node) node = document.getElementsByTagName("body")[0];
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
    if(re.test(els[i].className))a.push(els[i]);
    return a;
}

var nextObject = function(elm) {
  var n = elm;
  do n = n.nextSibling;
  while (n && n.nodeType != 1);
  return n;
};

var previousObject = function(elm) {
  var p = elm;
  do p = p.previousSibling;
  while (p && p.nodeType != 1);
  return p;
};

function pridatTargetBlank (elmClassName) {
    $('a.'+elmClassName).click( function() {
        window.open(this.href,"new_window","width=505,height=505");
        return false;
    });
};

function nastavitAkceProGalerie (elmClassName) {
    var elms = document.getElementsByTagName('a');
    for (var i = 0; i < elms.length; i++) {
        if (elms[i].className == elmClassName) {
            elms[i].onmousedown = zmenDetailGalerie;
            elms[i].href = "javascript: void(0)";
        }
    }
};

function zmenDetailGalerie (e) {
    e = (e) ? e : window.event;
    var nosic;
    if (e.target) nosic = e.target;
    else if (e.srcElement) nosic = e.srcElement;
    if (nosic.nodeType == 3) nosic = nosic.parentNode;
    if (nosic.tagName == 'IMG') nosic = nosic.parentNode;
    var castiId = nosic.id.split('_');
    var detailElm = document.getElementById('img_detail_'+castiId[1]);
    var newDetailHTML = '<a href="'+eval('images_'+castiId[1]+'["imgUrls"]')+castiId[2]+'/full.jpg" target="_blank">\n';
    var imageSizeString = eval('images_'+castiId[1]+'["'+castiId[2]+'_size"]');
    var imageSize = new Array();
    imageSize = imageSizeString.split('_');
    
    newDetailHTML = newDetailHTML + '<img src="'+eval('images_'+castiId[1]+'["imgUrls"]')+castiId[2]+'/'+eval('images_'+castiId[1]+'["fileNms"]')+'" alt="'+eval('images_'+castiId[1]+'["'+castiId[2]+'"]')+'" width="'+imageSize[0]+'" height="'+imageSize[1]+'" />\n';
    newDetailHTML = newDetailHTML + '</a>\n';
    
    detailElm.innerHTML = newDetailHTML; 
    return true;
};

function nastavitMenu (parentId) {
    var liElms = document.getElementsByTagName('li');
    for (var i = 0; i < liElms.length; i++) {
        if (((liElms[i].parentElement) && (liElms[i].parentElement.id == parentId)) || ((liElms[i].parentNode) && (liElms[i].parentNode.id == parentId))) {
            liElms[i].onmouseover = zobrazPodmenu;
            liElms[i].onmouseout = skryjPodmenu;
        }
    }
};

function zobrazPodmenu(e) {
    e = (e) ? e : window.event;
    var nosic;
    if (e.target) nosic = e.target;
    else if (e.srcElement) nosic = e.srcElement;
    if (nosic.tagName == 'A') nosic = nosic.parentNode;
    
    var ulElms = document.getElementsByTagName('ul');
    for (var i = 0; i < ulElms.length; i++) {
        if (((ulElms[i].parentElement) && (ulElms[i].parentElement == nosic)) || ((ulElms[i].parentNode) && (ulElms[i].parentNode == nosic))) {
            ulElms[i].style.filter = 'alpha(opacity=10)';
            ulElms[i].style.opacity = '.1';
            ulElms[i].style.display = 'block';
            ulElms[i].onmouseover = zobrazMenu;
            ulElms[i].onmouseout = skryjMenu;
            setTimeout('fadeToMaximum(\''+ulElms[i].id+'\',0,5,25)',25); // id of element, init percents, percent by one round
        }
    }
};

function fadeToMaximum(elmId,initPerc,percByRound,timeByRound) {
    var targetOpacity = 100;
    if (initPerc < targetOpacity) {
        var elm = document.getElementById(elmId);
        var newPercnets = ((initPerc + percByRound) < targetOpacity) ? (initPerc + percByRound) : targetOpacity;
        elm.style.filter = 'alpha(opacity='+newPercnets+')';
        elm.style.opacity = newPercnets / 100;
        setTimeout('fadeToMaximum(\''+elmId+'\','+newPercnets+','+percByRound+','+timeByRound+')',timeByRound);    
    }
};

function skryjPodmenu(e) {
    e = (e) ? e : window.event;
    var nosic;
    if (e.target) nosic = e.target;
    else if (e.srcElement) nosic = e.srcElement;
    if (nosic.tagName == 'A') nosic = (nosic.parentNode) ? nosic.parentNode : nosic.parentElement;
    
    var ulElms = document.getElementsByTagName('ul');
    for (var i = 0; i < ulElms.length; i++) {
        if (((ulElms[i].parentElement) && (ulElms[i].parentElement == nosic)) || ((ulElms[i].parentNode) && (ulElms[i].parentNode == nosic))) {
            ulElms[i].style.display = 'none';
        }
    }
};

function zobrazMenu(e) {
    e = (e) ? e : window.event;
    var nosic;
    if (e.target) nosic = e.target;
    else if (e.srcElement) nosic = e.srcElement;
    if (nosic.tagName == 'LI') nosic = (nosic.parentNode) ? nosic.parentNode : nosic.parentElement;
    if (nosic.tagName == 'A') nosic = (nosic.parentNode) ? nosic.parentNode.parentNode : nosic.parentElement.parentElement;
    
    nosic.style.display = 'block';
};

function skryjMenu(e) {
    e = (e) ? e : window.event;
    var nosic;
    if (e.target) nosic = e.target;
    else if (e.srcElement) nosic = e.srcElement;
    if (nosic.tagName == 'LI') nosic = (nosic.parentNode) ? nosic.parentNode : nosic.parentElement;
    if (nosic.tagName == 'A') nosic = (nosic.parentNode) ? nosic.parentNode.parentNode : nosic.parentElement.parentElement;
    
    nosic.style.display = 'none';
};

function changeComDis (newStyleDisp,targetClass) {
    var trElms = document.getElementsByTagName('tr');
    for (var i = 0; i < trElms.length; i++) {
        if (trElms[i].className == targetClass) {
            trElms[i].style.display = newStyleDisp;
        }
    }
};

function skryj(elmId,className,elmType) {
    if (!className) {
        document.getElementById(elmId).style.display = 'none';
    } else {
        var elms = document.getElementsByTagName(elmType);
        for (var i = 0; i < elms.length; i++) {
            if (elms[i].className == className) elms[i].style.display = 'none';
        }
    }
    return false;
}

function zobraz(elmId,className,elmType) {
    if (!className) {
        document.getElementById(elmId).style.display = '';
    } else {
        var elms = document.getElementsByTagName(elmType);
        for (var i = 0; i < elms.length; i++) {
            if (elms[i].className == className) elms[i].style.display = '';
        }
    }
    return false;
}

var correctHref = 0;

function checkPhone () {
    if (getCheckedValue('shipment_type') == '15') {
        alert(window.noPhoneMess);
        return false;
        if (document.getElementById('orderer_phone').value.length < 9) {
            alert(window.noPhoneMess);
            linkElm.href = 'javascript:void(0)';
            return false;
        } else {
            return true;
        }
    }
}

function checkRuleSubmit (ruleElmId,linkElmId) {
    var ruleElm = document.getElementById(ruleElmId);
    var linkElm = document.getElementById(linkElmId);
    if (window.correctHref == 0) window.correctHref = linkElm.href;
    if (ruleElm && linkElm) {
        if (ruleElm.checked) {
            linkElm.href = window.correctHref;
            return true;
        } else {
            alert(window.noRulesMess);
            linkElm.href = 'javascript:void(0)';
            return false;
        }
    }
}

function addBBcode (type, targetId) {
    var targetElm = document.getElementById(targetId);
    var html = targetElm.value;
    switch(type)
    {
    case 'b':
      html = html + '[b][/b]';
      break;
    case 'i':
      html = html + '[i][/i]';
      break;
    case 'u':
      html = html + '[u][/u]';
      break;
    case 'img':
      html = html + '[img][/img]';
      break;
    case 'url':
      html = html + '[url=""][/url]';
      break;
    }
    targetElm.value = html;
}

function validateShipmentSelection (newValue) {
    // allowed[newValue] -> array of allowed values for payment
    var paymentInput = document.shipment.payment_type;
    var actualPaymentVal = getCheckedValue(paymentInput);
    if (!in_array(actualPaymentVal,window.allowed[newValue])) {
        setCheckedValue(paymentInput,window.allowed[newValue][0]);
    }
    var allInputs = document.getElementsByTagName('input');
    for (var i = 0; i < allInputs.length; i++) {
        for (var y = 0; y < 25; y++) {
            if (allInputs[i].id == 'payment_type_'+y) {
                if (in_array(y,window.allowed[newValue])) {
                    allInputs[i].disabled = false;
                } else {
                    allInputs[i].disabled = true;
                }                
            }
        }
    }
}

function changeDelFormVisibility (i, formElmId) {
    var elm = document.getElementById(formElmId);
    if (elm) {
        elm.style.display = window.deliveryFormDisplay[i];
    }
}

// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function setCheckedValue(radioObj, newValue) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}

function in_array (needle, haystack, argStrict) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true
    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false
 
    var key = '', strict = !!argStrict;
 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }
 
    return false;
}




/* Thanks to http://techpatterns.com/downloads/javascript_cookies.php */

function Set_Cookie( name, value, expires, path, domain, secure )
{
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime( today.getTime() );
    
    /*
    if the expires variable is set, make the correct
    expires time, the current script below will set
    it for x number of days, to make it for hours,
    delete * 24, for minutes, delete * 60 * 24
    */
    if ( expires )
    {
    expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date( today.getTime() + (expires) );
    
    document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}

function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
    if ( Get_Cookie( name ) ) document.cookie = name + "=" +
    ( ( path ) ? ";path=" + path : "") +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

