//var wh = new Array();		
//var marker = new Array();
$(document).ready(function(){

  /* 27.05.2011 */
  //initCustomFile();						   
  initCustomFile2()
  /* /27.05.2011 */
  
  $('input.move_right').bind('click', function(){
	  var t = $(this).parents('table.pare');
	  var idl = $('select.left', t).attr('id');
	  var idr = $('select.right', t).attr('id');
	  
	  var id = '';
	  var txt = '';
	  var html = ''
	  
	  html = $('#'+idr).html();
	  $('#' + idl + ' :selected').each(function(i, selected){
		  txt = $(selected).text();
		  id = $(selected).val();
		  
		  $(selected).remove();
		  
		  html = html + '<option value="' + id + '">' + txt + '</option>';
	  });	
	  $('#'+idr).html(html);
	  $('select.left', t).focus();
	  return false;
  });
  
  
  $('input.move_right_all').bind('click', function(){
	  var t = $(this).parents('table.pare');
	  var idl = $('select.left', t).attr('id');
	  var idr = $('select.right', t).attr('id');
	  
	  var id = '';
	  var txt = '';
	  var html = ''
	  
	  html = $('#'+idr).html();
	  $('#' + idl + ' option').each(function(i, selected){
		  txt = $(selected).text();
		  id = $(selected).val();
		  
		  $(selected).remove();
		  
		  html = html + '<option value="' + id + '">' + txt + '</option>';
	  });	
	  $('#'+idr).html(html);
	  $('select.left', t).focus();	
	  return false;
  });
  
  
  $('input.move_left').bind('click', function(){
	  var t = $(this).parents('table.pare');
	  var idl = $('select.left', t).attr('id');
	  var idr = $('select.right', t).attr('id');
	  
	  var id = '';
	  var txt = '';
	  var html = ''
	  
	  html = $('#'+idl).html();
	  $('#' + idr + ' :selected').each(function(i, selected){
		  txt = $(selected).text();
		  id = $(selected).val();
		  
		  $(selected).remove();
		  
		  html = html + '<option value="' + id + '">' + txt + '</option>';
	  });	
	  $('#'+idl).html(html);
	  $('select.left', t).focus();	
	  return false;	
  });
  
  
  $('input.move_left_all').bind('click', function(){
	  var t = $(this).parents('table.pare');
	  var idl = $('select.left', t).attr('id');
	  var idr = $('select.right', t).attr('id');
	  
	  var id = '';
	  var txt = '';
	  var html = ''
	  
	  html = $('#'+idl).html();
	  $('#' + idr + ' option').each(function(i, selected){
		  txt = $(selected).text();
		  id = $(selected).val();
		  
		  $(selected).remove();
		  
		  html = html + '<option value="' + id + '">' + txt + '</option>';
	  });	
	  $('#'+idl).html(html);
	  $('select.left', t).focus();	
	  return false;	
  });
  
  $("form#poll_form input[type='radio']").bind('click', function(){
	  $("form#poll_form input[type='submit']").removeAttr('disabled');
  });
  
  if ($('.slider').length > 0) {
  $( ".slider2" ).slider({
		  min: 0,
		  max: 100,
		  slide: function(event, ui) {
			  var v = ui.value;
			  var target = event.target;
			  $(target).parents('.slider-holder').find('input').val(v)
		  }
   });			
  }	
  if ($('#carousel').length > 0) {
    $('#carousel').jcarousel();
  }
   
    $('.slider-holder a.minus').bind('click', function(){
		var slider = $(this).parents('td:first').find('.slider2');
		var v = $(slider).slider('option', 'value');
		v = parseInt(v);
		if (v > 0) v = v - 1;
		$(slider).slider('option', 'value', v);
        $(this).parents('.slider-holder').find('input').val(v);
		return false;
	});
	
    $('.slider-holder a.plus').bind('click', function(){
		var slider = $(this).parents('td:first').find('.slider2');
		var v = $(slider).slider('option', 'value');
		v = parseInt(v);
		if (v < 100) v = v + 1;
		$(slider).slider('option', 'value', v);
		$(this).parents('.slider-holder').find('input').val(v);
		return false;		
	});
	

});

function send_form() {
	var txt1 = '';
	$('select#drugs_right option').each(function(i, dr){
		txt1 = txt1 + ':' + $(dr).text();
	});
	$('input[name=f_Drugs]').val(txt1);

	var txt2 = '';
	$('select#procedures_right option').each(function(i, pr){
		txt2 = txt2 + ':' + $(pr).text();
	});
	$('input[name=f_Procedures]').val(txt2);


	var txt3 = '';
	$('select#procedures2_right option').each(function(i, pr){
		txt3 = txt3 + ':' + $(pr).text();
	});
	$('input[name=f_Procedures2]').val(txt3);
	
	var res = true;
	res = res && ($('input[name=f_Name]').val() != '');
	res = res && ($('input[name=f_Address]').val() != '');
	res = res && ($('input[name=f_Phone]').val() != '');
	res = res && ($('textarea[name=f_Short]').val() != '');
	res = res && ($('textarea[name=f_Description]').val() != '');
	
	if (!res) {
		alert('Не все обязательные поля заполнены');
		return false;
	}
	
	var town = $('select[name=f_Town]').val();
	if (parseInt(town) == 1) {
		var district = $('select[name=f_District]').val();
		var metro = $('select[name=f_Metro]').val();
		if (parseInt(district) == 0 || parseInt(metro) == 0) {
			alert('Для Москвы нужно указать округ и станцию метро');
			return false;
		}
	}
	
	if (txt1 == '' && txt2 == '' && txt3 == '') {
		alert('Должно быть заполнено хотя бы одно из полей отмеченных (***)');
		return false;
	} 
	
	var qid = $('input[name=secret_question]').val();
	var answer = $('input[name=secret_answer]').val();
	
	$.post('/ajax/check_answer.php', {qid:qid, answer:answer}, function(data){
		if (data == '0') {
			alert('Вы неправильно ответили на контрольный вопрос');
			return false;
		} else {
			document.adminForm.submit();
		}
	});
}


function send_form2(nosecret) {
	var txt1 = '';
	$('select#drugs_right option').each(function(i, dr){
		txt1 = txt1 + ':' + $(dr).text();
	});
	$('input[name=f_Drugs]').val(txt1);

	var txt2 = '';
	$('select#procedures_right option').each(function(i, pr){
		txt2 = txt2 + ':' + $(pr).text();
	});
	$('input[name=f_Procedures]').val(txt2);


	var txt3 = '';
	$('select#procedures2_right option').each(function(i, pr){
		txt3 = txt3 + ':' + $(pr).text();
	});
	$('input[name=f_Procedures2]').val(txt3);
	
	var res = true;
        /*
	res = res && ($('input[name=f_Name]').val() != '');
	res = res && ($('input[name=f_Address]').val() != '');
	res = res && ($('input[name=f_Phone]').val() != '');
	res = res && ($('textarea[name=f_Short]').val() != '');
	res = res && ($('textarea[name=f_Description]').val() != '');
	
	if (!res) {
		alert('Не все обязательные поля заполнены');
		return false;
	}
        */
	
        /*
	var town = $('select[name=f_Town]').val();
	if (parseInt(town) == 1) {
		var district = $('select[name=f_District]').val();
		var metro = $('select[name=f_Metro]').val();
		if (parseInt(district) == 0 || parseInt(metro) == 0) {
			alert('Для Москвы нужно указать округ и станцию метро');
			return false;
		}
	}
	
	if (txt1 == '' && txt2 == '' && txt3 == '') {
		alert('Должно быть заполнено хотя бы одно из полей отмеченных (***)');
		return false;
	} 
	*/
	
	var exist = $('input[name=secret_question]').length > 0 && $('input[name=secret_answer]').length > 0;

	
	if (!nosecret && exist) {
		var qid = $('input[name=secret_question]').val();
		var answer = $('input[name=secret_answer]').val();
		$.post('/ajax/check_answer.php', {qid:qid, answer:answer}, function(data){
			if (data == '0') {
				alert('Вы неправильно ответили на контрольный вопрос');
				return false;
			} else {
				document.adminForm.submit();
			}
		});
	} else {
		document.adminForm.submit();
	}
}



function search_form() {
	var txt1 = '';
	$('select#drugs_right option').each(function(i, dr){
		txt1 = txt1 + ':' + $(dr).val();
	});
	$('input[name=f_Drugs]').val(txt1);

	var txt2 = '';
	$('select#procedures_right option').each(function(i, pr){
		txt2 = txt2 + ':' + $(pr).val();
	});
	$('input[name=f_Procedures]').val(txt2);


	var txt3 = '';
	$('select#procedures2_right option').each(function(i, pr){
		txt3 = txt3 + ':' + $(pr).val();
	});
	$('input[name=f_Procedures2]').val(txt3);
	
	document.sform.submit();	
	return false;
}



function switch_town() {
    //return;
	if ($('#notfound').length == 1) {
		document.stform.submit();
	}
	
    var town = $('select[name=town]').val();
    var ind = array_search(town, map_names);
    if (ind) {
        ind = parseInt(ind);
        ind++;
        var x = parseFloat(map_data[ind][0]);
        var y = parseFloat(map_data[ind][1]);
        var z = parseInt(map_data[ind][2]);
        map.setCenter(new GLatLng(x, y), z);
    }
    rebuild_markers();
}


function rebuild_markers() {
    map.clearOverlays();
    var town = $('select[name=town]').val();
    var metro = $('select[name=metro]').val();
    var drugs = '';
    var proc = '';
    var proc2 = '';

    // Если выбрано метро, то будем позиционировать карту на этом метро
	if (parseInt(metro) > 0) {
		switch_metro();
	}
	
    // Подготовка данных для условий отбора
    $('select[name=drugs] option:selected').each(function(i, opt){
        drugs = drugs + ':' + $(opt).val();
    });
	//var drugs_way = $('input[name=drugs_way]').val();
	
    $('select[name=procedures] option:selected').each(function(i, opt){
        proc = proc + ':' + $(opt).val();
    });
	//var proc_way = $('input[name=proc_way]').val();
	
    $('select[name=procedures2] option:selected').each(function(i, opt){
        proc2 = proc2 + ':' + $(opt).val();
    });
	//var proc2_way = $('input[name=proc2_way]').val();
	
    $.post('/ajax/markers.php', {town:town, metro:metro, drugs:drugs, proc:proc, proc2:proc2}, function(data){
		//$('#map').before(data);
		//return;
		//data = unserialize(data);
        var i = "0";
        var m = '';
        var j = 1;

        for(i in data) {
            var ob = data[i];
            var wh = '<b><a href="' + ob.link + '" target=_blank>' + ob.Name + '</a></b><br>' + ob.Address + '<br>Телефон: ' + ob.Phone;
            /*var marker[j] = new GMarker(new GLatLng(parseFloat(ob.XCoord), parseFloat(ob.YCoord)));
            map.addOverlay(marker[j]);
            GEvent.addListener(marker[j], 'click', function() {
                marker[j].openInfoWindowHtml(wh[j]);
            });
			*/
            map.addOverlay(createMarker(parseFloat(ob.XCoord), parseFloat(ob.YCoord), wh));			
            j++;
        }
    }, "json");
	// , "json"
}

function createMarker(x, y, comment) {  
    // Создаем точку на карте с координатами x и y  
    var point = new GLatLng(x, y);  
      
    // Создаем маркер в указанной точке  
    var marker = new GMarker(point);  
       
    // Добавляем обработчик события нажатия на маркер  
    GEvent.addListener(marker, "click", function() {  
        // При нажатии открывается информационное окно с заданным текстом  
        marker.openInfoWindowHtml(comment);  
    });  
      
    return marker;  
} 

function switch_metro() {
    //return;
    var metro = $('select[name=metro] option:selected').text();
    var ind = array_search(metro, metro_names);
    if (ind) {
        ind = parseInt(ind);
        ind++;
        var x = parseFloat(metro_data[ind][0]);
        var y = parseFloat(metro_data[ind][1]);
        var z = parseInt(metro_data[ind][2]);
        map.setCenter(new GLatLng(x, y), z);
    }
}

function array_search( needle, haystack, strict ) {    // Searches the array for a given value and returns the corresponding key if
    var strict = !!strict;
 
    for(var key in haystack){
        if( (strict && haystack[key] === needle) || (!strict && haystack[key] == needle) ){
            return key;
        }
    }
    return false;
}

function unserialize(data){
    // Creates a PHP value from a stored representation
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_unserialize/
    // +       version: 809.2122
    // +     original by: Arpad Ray (mailto:arpad@php.net)
    // +     improved by: Pedro Tainha (http://www.pedrotainha.com)
    // +     bugfixed by: dptr1988
    // +      revised by: d3x
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %            note: We feel the main purpose of this function should be to ease the transport of data between php & js
    // %            note: Aiming for PHP-compatibility, we have to translate objects to arrays 
    // *       example 1: unserialize('a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}');
    // *       returns 1: ['Kevin', 'van', 'Zonneveld']
    // *       example 2: unserialize('a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}');
    // *       returns 2: {firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'}
    
    var error = function (type, msg, filename, line){throw new window[type](msg, filename, line);};
    var read_until = function (data, offset, stopchr){
        var buf = [];
        var chr = data.slice(offset, offset + 1);
        var i = 2;
        while(chr != stopchr){
            if((i+offset) > data.length){
                error('Error', 'Invalid');
            }
            buf.push(chr);
            chr = data.slice(offset + (i - 1),offset + i);
            i += 1;
        }
        return [buf.length, buf.join('')];
    };
    var read_chrs = function (data, offset, length){
        buf = [];
        for(var i = 0;i < length;i++){
            var chr = data.slice(offset + (i - 1),offset + i);
            buf.push(chr);
        }
        return [buf.length, buf.join('')];
    };
    var _unserialize = function (data, offset){
        if(!offset) offset = 0;
        var buf = [];
        var dtype = (data.slice(offset, offset + 1)).toLowerCase();
        
        var dataoffset = offset + 2;
        var typeconvert = new Function('x', 'return x');
        var chrs = 0;
        var datalength = 0;
        
        switch(dtype){
            case "i":
                typeconvert = new Function('x', 'return parseInt(x)');
                var readData = read_until(data, dataoffset, ';');
                var chrs = readData[0];
                var readdata = readData[1];
                dataoffset += chrs + 1;
            break;
            case "b":
                typeconvert = new Function('x', 'return (parseInt(x) == 1)');
                var readData = read_until(data, dataoffset, ';');
                var chrs = readData[0];
                var readdata = readData[1];
                dataoffset += chrs + 1;
            break;
            case "d":
                typeconvert = new Function('x', 'return parseFloat(x)');
                var readData = read_until(data, dataoffset, ';');
                var chrs = readData[0];
                var readdata = readData[1];
                dataoffset += chrs + 1;
            break;
            case "n":
                readdata = null;
            break;
            case "s":
                var ccount = read_until(data, dataoffset, ':');
                var chrs = ccount[0];
                var stringlength = ccount[1];
                dataoffset += chrs + 2;
                
                var readData = read_chrs(data, dataoffset+1, parseInt(stringlength));
                var chrs = readData[0];
                var readdata = readData[1];
                dataoffset += chrs + 2;
                if(chrs != parseInt(stringlength) && chrs != readdata.length){
                    error('SyntaxError', 'String length mismatch');
                }
            break;
            case "a":
                var readdata = {};
                
                var keyandchrs = read_until(data, dataoffset, ':');
                var chrs = keyandchrs[0];
                var keys = keyandchrs[1];
                dataoffset += chrs + 2;
                
                for(var i = 0;i < parseInt(keys);i++){
                    var kprops = _unserialize(data, dataoffset);
                    var kchrs = kprops[1];
                    var key = kprops[2];
                    dataoffset += kchrs;
                    
                    var vprops = _unserialize(data, dataoffset);
                    var vchrs = vprops[1];
                    var value = vprops[2];
                    dataoffset += vchrs;
                    
                    readdata[key] = value;
                }
                
                dataoffset += 1;
            break;
            default:
                error('SyntaxError', 'Unknown / Unhandled data type(s): ' + dtype);
            break;
        }
        return [dtype, dataoffset - offset, typeconvert(readdata)];
    };
    return _unserialize(data, 0)[2];
}// }}}


function initCustomFile() {
	$('div.custom-file').each(function() {
		if(!$(this).hasClass('custom-file-implemented')) {
			var customFileHolder = $(this);
			var customFileIn = $('.custom-file-input', customFileHolder);
			var customFileOut = $('.custom-file-output', customFileHolder);
			customFileIn.attr('readOnly', true);
			
			customFileOut.change(function() {
				customFileIn.val($(this).val());
			});
			
			customFileHolder.addClass('custom-file-implemented');
		}
	});
}

/* 27.05.2011 */
function initCustomFile2() {
  $('#file').change(function() {
	  $('#file').each(function() {
		  var name = this.value;
		  reWin = /.*\\(.*)/;
		  var fileTitle = name.replace(reWin, "$1");
		  reUnix = /.*\/(.*)/;
		  fileTitle = fileTitle.replace(reUnix, "$1");
		  $('#filename').html(fileTitle);
	 });
  });
}
/* /27.05.2011 */




/*
if (window.addEventListener)
	window.addEventListener("load", initCustomFile, false);
else if (window.attachEvent)
	window.attachEvent("onload", initCustomFile);
	
*/	

function slider_reset() {
	$('.slider2').each(function(){
	    $(this).slider('option', 'value', '0');
	    $(this).parents('.slider-holder').find('input').val('0')		
	});
	return false;
}


function slider_middle() {
	$('.slider2').each(function(){
	    $(this).slider('option', 'value', '50');
	    $(this).parents('.slider-holder').find('input').val('50')		
	});
	return false;
}

function slider_max() {
	$('.slider2').each(function(){
	    $(this).slider('option', 'value', '100');
	    $(this).parents('.slider-holder').find('input').val('100')				
	});
	return false;	
}

function send_link() {
	var vals = $('form#form_send_link').serialize();
	$.post('/info/vizualization/sendlink/?template=96', vals, function(data){
		$('div#basic-modal-content').html(data);
    });
	return false;
}



