
// Служебные функции
// код функций getPageScroll() и getPageSize() взят из бибилиотеки Lightbox2 (http://www.huddletogether.com/projects/lightbox2/)

// Returns array with x,y page scroll values.
// Core code from - quirksmode.com
function getPageScroll(){
	var xScroll, yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) { // all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;
	}

	arrayPageScroll = new Array(xScroll,yScroll)
	return arrayPageScroll;
}

// Returns array with page width, height and window width, height
// Core code from - quirksmode.com
// Edit for Firefox by pHaez
function getPageSize(){

	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	}
	else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	}
	else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}


	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth;
		}
		else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	}
	else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	}
	else {
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = xScroll;
	} else {
		pageWidth = windowWidth;
	}

	arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight)
	return arrayPageSize;
}

// ---------------------------------------------------

function showSelectBoxes(){
	var selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "visible";
	}
}

// ---------------------------------------------------

function hideSelectBoxes(){
	var selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "hidden";
	}
}


// Работа с блоком вывода информации над контентом страницы
// *****************************************************************************

// Формирование блока оверлэя
function makeOverlay() {
	hideSelectBoxes();
	var overBox = document.getElementById('overlay');
	overBox.style.display = 'block';
	// Назначаем прозрасность элементу
	if(/MSIE/.test(navigator.userAgent)) { overBox.style.filter = 'alpha(opacity=65)';} //Если это контуженый по колено Осел
	else { overBox.style.opacity = 0.65;} // коли нормальный браузер

	// Устанавливаем высоту div'а
	var wSize = getPageSize();
	overBox.style.height = wSize[1];

	return false;
}

function closeOverlay() {
	showSelectBoxes();
	var overBox = document.getElementById('overlay');
	overBox.style.display = 'none';
	overBox.innerHTML = '';

	var infoBox = document.getElementById('infoBox');
	infoBox.style.display = 'none';
	infoBox.innerHTML = '';
}


// Создание контейнера для показа
function makeBox(videoWidth, videoHeight, videoNote){
	makeOverlay();
	var infoBox = document.getElementById('infoBox');
	infoBox.style.display = 'block';

	// Устанавливаем отступ от верхнего края до места показа
	var wSize = getPageSize();
	var wScroll = getPageScroll();
	infoBox.style.top = wScroll[1]+wSize[3]/2-videoHeight/2;

	var infoContent = '<table class="videoView" align="center" style="width: '+videoWidth+';"> '
				+'<tr><td align=center class=video>';
	infoContent += '<div id="overlayPlayer"></div>';
	infoContent += '</td><td class="close"><img onClick="closeOverlay(); return false;" '
				+'src="/i/ico_close_13x13_grey.gif" width="13" height="13" border="0" alt="[x]" title="закрыть" /></div>'
	infoContent += '</td></tr>';
	if(videoNote){
		infoContent +='<tr><td class="videoNote" style="padding:10px">'+videoNote+'</td><td></td></tr>';
	}
	infoContent += '</table>';
	
	infoBox.innerHTML = infoContent;
	
};

// *****************************************************************************
function showBuy(vTitle, vWidth, vHeight, vItem, vOwner) {
	// Если функцию вызвали без параметров - не работаем
	if(!arguments.length) return false;
	// Определяемся с умолчаниями для аргументов функции
	if(!vWidth) vWidth = 350;
	if(!vHeight) vHeight = 300;
	
	// Запускаем просмотр
	makeBox(vWidth, vHeight, '');

   vTitleFull=str_replace(' ',"***",vTitle);
   vTitleFull=str_replace("\"","",vTitleFull);    
   
	infoContent1="<form name=\"buyform\" id=\"buyform\" action='/buy_ajax.php' onsubmit=\"return false;\" style='margin:0; padding:0'><input type=hidden name=title id=title value="+vTitleFull+"><input type=hidden name=item id=item value="+vItem+"><input type=hidden name=owner id=owner value="+vOwner+"><div id='trash'><table width=100% height=100% cellspacing=5><tr><td colspan=2 align=center style='background:#82050B'><b style='color:#ffffff'>ФОРМА ЗАКАЗА</b></td></tr><tr><td width=25% class=textfirms align=right>Наименование:</td><td style='font-size:11px'>"+vTitle+"</td></tr><tr><td class=textfirms align=right>Количество:</td><td><input type=text name='kolvo' id=\"kolvo\" style='width:100%' value=1></td></tr><tr><td class=textfirms align=right>Ваше ФИО*:</td><td><input type=text name='fio' id=\"fio\" style='width:100%'></td></tr><tr><td class=textfirms align=right>Телефон*:</td><td><input type=text name='phone' id=\"phone\" style='width:100%'></td></tr><tr><td class=textfirms align=right>E-mail:</td><td><input type=text name='email' id=\"email\" style='width:100%'></td></tr><tr><td class=textfirms align=right>Адрес:</td><td><input type=text name='address' id=\"address\" style='width:100%'></td></tr><tr><td class=textfirms align=right>Комментарий:</td><td><textarea name='comms' id=\"comms\" style='width:100%; height:50px'></textarea></td></tr><tr><td colspan=2 align=center><br><input type=button id=pressbut value='ПОДТВЕРДИТЬ' onclick=\"__doExecute('trash', {}, '/buy_ajax.php', 'buyform'); pressbut.style.visibility='hidden'; return false;\"><br><br></td></tr></table></div></form>";
	
overlayPlayer.innerHTML = infoContent1;
}


function showAsk(vTitle, vWidth, vHeight, vItem, vOwner) {
	// Если функцию вызвали без параметров - не работаем
	if(!arguments.length) return false;
	// Определяемся с умолчаниями для аргументов функции
	if(!vWidth) vWidth = 350;
	if(!vHeight) vHeight = 300;
	
	// Запускаем просмотр
	makeBox(vWidth, vHeight, '');

   vTitleFull=str_replace(' ',"***",vTitle);
   vTitleFull=str_replace("\"","",vTitleFull);    
   
	infoContent1="<form name=\"buyform\" id=\"askform\" action='/ask_ajax.php' onsubmit=\"return false;\" style='margin:0; padding:0'><input type=hidden name=title id=title value="+vTitleFull+"><input type=hidden name=item id=item value="+vItem+"><input type=hidden name=owner id=owner value="+vOwner+"><div id='trash'><table width=100% height=100% cellspacing=5><tr><td colspan=2 align=center style='background:#82050B'><b style='color:#ffffff'>ЗАДАЙТЕ СВОЙ ВОПРОС</b></td></tr><tr><td width=25% class=textfirms align=right>Наименование:</td><td style='font-size:11px'>"+vTitle+"</td></tr><tr><td class=textfirms align=right>Ваше ФИО*:</td><td><input type=text name='fio' id=\"fio\" style='width:100%'></td></tr><tr><td class=textfirms align=right>Телефон:</td><td><input type=text name='phone' id=\"phone\" style='width:100%'></td></tr><tr><td class=textfirms align=right>E-mail*:</td><td><input type=text name='email' id=\"email\" style='width:100%'></td></tr><tr><td class=textfirms align=right>Вопрос*:</td><td><textarea name='comms' id=\"comms\" style='width:100%; height:50px'></textarea></td></tr><tr><td colspan=2 align=center><br><input type=button id=pressbut value='ОТПРАВИТЬ' onclick=\"__doExecute('trash', {}, '/ask_ajax.php', 'askform'); pressbut.style.visibility='hidden'; return false;\"><br><br></td></tr></table></div></form>";
	
overlayPlayer.innerHTML = infoContent1;
}

function str_replace ( search, replace, subject ) {    // Replace all occurrences of the search string with the replacement string
    // 
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
 
    if(!(replace instanceof Array)){
        replace=new Array(replace);
        if(search instanceof Array){//If search    is an array and replace    is a string, then this replacement string is used for every value of search
            while(search.length>replace.length){
                replace[replace.length]=replace[0];
            }
        }
    }
 
    if(!(search instanceof Array))search=new Array(search);
    while(search.length>replace.length){//If replace    has fewer values than search , then an empty string is used for the rest of replacement values
        replace[replace.length]='';
    }
 
    if(subject instanceof Array){//If subject is an array, then the search and replace is performed with every entry of subject , and the return value is an array as well.
        for(k in subject){
            subject[k]=str_replace(search,replace,subject[k]);
        }
        return subject;
    }
 
    for(var k=0; k<search.length; k++){
        var i = subject.indexOf(search[k]);
        while(i>-1){
            subject = subject.replace(search[k], replace[k]);
            i = subject.indexOf(search[k],i);
        }
    }
 
    return subject;
 
}