function a1()
{
	var $productselect = $('#product-selector').children('select');
	var $infobar       = $('#infobar');
	var $actionform    = $('#actionform');
	data = [{"prodPic":null,"prodId":"667","prodCode":"EVE 1","prodPrice":"2"}, {"prodPic":null,"prodId":"669","prodCode":"EVE 2","prodPrice":"2"}];

	function beatifyProductSelect() 
	{
		if (!$('#product-buttons').length) 
		{
			$productselect.parent().after('<ul class="btn-list" id="product-buttons">');
        }
        $('#product-buttons').empty();

        $productselect.children().each(function(i)
        {
        	var $product = $('<li><a name="ut_code_price" href="#"><span>' + $(this).html() + '</span></a></li>').
                                    click(function(){
                                        $productselect.get(0).selectedIndex = i;
                                        $productselect.change();
        		                        
                                        return false;
                                    });
        	if ($productselect.get(0).selectedIndex == i) 
        	{
        		$product.addClass('active');
        	}
        	
        	$('#product-buttons').append($product);
        	
        })

        $productselect.change(function()
        {
        	$($('#product-buttons').children('li').removeClass('active').get($productselect.get(0).selectedIndex)).addClass('active');
        })
        $productselect.parent().hide(); // hide select
	}
	
	$productselect.empty();
    $(data).each(function()
    {
    	$productselect.append("<option value=" + this.prodId  +">" + this.prodCode + ' — ' + this.prodPrice + ' RUR</option>');
    })
            
    beatifyProductSelect();

    $infobar.stop().hide();
    $actionform.stop().css('opacity', 1). show();
}

$(document).ready(function(){
    var requestUrl = location.href;
    var baseUrl = document.location.href.replace(document.location.search, '');
    var phoneFieldOnId = 12;
    var selectedProd = 0;
    /*$('.article').parent().click(function(event){
    	window.location.assign(event.target);
    });*/

    // Cached Objects
    var $items         = $('#content .game-list li');
    var $infobar       = $('#infobar');
    var $actionform    = $('#actionform');
    var $productselect = $('#product-selector').children('select');
    var $paymentselect = $('#payment').children('select');

    function beatifyProductSelect() {
        if (!$('#product-buttons').length) {
            $productselect.parent().after('<ul class="btn-list" id="product-buttons">');
        }
        $('#product-buttons').empty();

        $productselect.children().each(function(i){
            var $product = $('<li><a name="ut_code_price" href="#"><span>' + $(this).html() + '</span></a></li>').
                            click(function(){
                                $productselect.get(0).selectedIndex = i;
                                $productselect.change();
		                        
                                return false;
                            });

            if ($productselect.get(0).selectedIndex == i) {
                $product.addClass('active');
            }

            $('#product-buttons').append($product);
        })

        $productselect.change(function(){
            $($('#product-buttons').children('li').removeClass('active').get($productselect.get(0).selectedIndex)).addClass('active');
        })
        $productselect.parent().hide(); // hide select
    }

    beatifyProductSelect();

    $paymentselect.change(function() {
        if ($(this).val() == phoneFieldOnId) {
            $actionform.find('input[name=email3]').parents('div.wrap').slideDown();
        } else {
            $actionform.find('input[name=email3]').parents('div.wrap').slideUp();
        }
        switch($(this).val())
        {
	        case '0':
	    		$('#timetopay').text('');
	    	break;
        	case '8':
        		$('#timetopay').text('Прохождение оплаты - 5 минут');
        	break;
        	case '10':
        		$('#timetopay').text('Прохождение оплаты - 1.5 часа');
            break;
        	case '12':
        		$('#timetopay').text('Прохождение оплаты - 5 минут');
            break;
        	case '13':
        		$('#timetopay').text('Прохождение оплаты - 5 минут');
            break;
        }
    });
    $actionform.find('input[name=email3]').parents('div.wrap').hide();

    $('#content .game-list li').click(function(event){
        // animation
    	if(event.target.toString().match(baseUrl))
    	{
    		return false;
    	}
        $items.removeClass('active'); 
        $(this).addClass('active');
        
        $actionform.fadeOut('fast', function() {
            $infobar.stop().html('<strong>Загрузка ...</strong>').fadeIn('fast');
        });       

        // request
        var requestData = {"rType" : "selectedGame"};
        try {
            requestData["gameId"] = $(this).find('div.text-holder > a').attr('href')
                                        .replace(baseUrl, '').replace('?', '') // clean up
                                        .match(/gid=(\d+)/i)[1];
        } catch (e) {
            alert('Invalid link format, unable to parse selection id');
            return false;
        }
        
        $.post(requestUrl, requestData, function(data) {
        	if(typeof ClickTaleExec=='function') {
        	    ClickTaleExec("a1()");
        	}
        	
            $productselect.empty();
            $(data).each(function(){
                $productselect.append("<option value=" + this.prodId  +">" + this.prodCode + ' — ' + this.prodPrice + ' RUR</option>');
            })
            
            beatifyProductSelect();
            
            $infobar.stop().hide();
            $actionform.stop().css('opacity', 1). show();
        }, 'json');


        return false;
    }).css('cursor', 'pointer');
    
    $('#content .game-list li .text-holder a').mouseover(function(){
    	$(this).parent().parent().find('div.img-holder > h3').toggle();
    });
    
    $('#content .game-list li .text-holder a').mouseout(function(){
    	$(this).parent().parent().find('div.img-holder > h3').toggle();
    });

    var searchTid, $searchfield;
    $searchfield = $('#search');

    $searchfield
        .change(function(){
            // make a search
            var searchPhrase = $searchfield.val().toLowerCase();
            if (searchPhrase == '') {
                $items.show();
                return
            }

            $items.each(function(){
                var $itemLink = $(this).find('a');
                var itemTitle = $itemLink.text().toLowerCase();
                var itemTags  = $itemLink.attr('rel').split(',');
                
                var matched = false;

                if (itemTitle.indexOf(searchPhrase) > -1) {
                    matched = true;
                }

                for (var i = 0; i < itemTags.length; i++) {
                    if ($.trim(itemTags[i]).indexOf(searchPhrase) > -1) {
                        matched = true;
                        break;
                    }
                }

                if (matched) {
                    $(this).show();
                } else {
                    $(this).hide();
                };
            });
            return             
        })
        .keyup(function(){
            clearTimeout(searchTid);
            searchTid = setTimeout(function(){
                $searchfield.change();
            }, 200);
        })
        .focus(function(){
            if ($(this).val() == 'поиск') {
                $(this).val('');
            }
        })
        .parents('form').submit(function(){
            $searchfield.change();
            return false;
        })

    $('#header').find('.search .example a').add('.tags li a')
        .click(function(){
            $searchfield.val($(this).text()).change();
            return false;
        });
    
    $('ul.accordion').accordion({
		active: ".selected",
		autoHeight: false,
		header: ".opener",
		collapsible: true,
		event: "click"
	});

	$('ul.accordion2').accordion({
		autoHeight: false,
		header: ".opener",
		collapsible: true,
		fillSpace: true,
		event: "click"
	});
	
	$('#email').add('#confirmation').keyup(function(){
        // clean up
        $('#email').add('#confirmation').parent().removeClass('error');
        if ( $('#email').val().match(/^[\.\-_A-Za-z0-9]+?@[\.\-A-Za-z0-9]+?\.[A-Za-z0-9]{2,6}$/i) == null ) {
            $('#email').parent().addClass('error');
        }
        if ($('#confirmation').val() != $('#email').val()) {
            $('#confirmation').parent().addClass('error');
        }
    });

	$('#phone').mask('(999)999-99-99', {placeholder:" "});
	
	$('#license').click(function(){
		window.parent.openFadeIFrame('?ukey=auxpage_license&view=noframe');
		return false;
	});
	
	$('#privacy').click(function(){
		window.parent.openFadeIFrame('?ukey=auxpage_privacy&view=noframe');
		return false;
	});
	
    //$('#submitSubscribe').click(function(){
	$('.subscription').submit(function(event){
		event.preventDefault();
    	var requestData = {"rType" : "subscribe"};
    	requestData["sEmail"] = $('#subscribe_only').val();
        $.post(requestUrl, requestData, function(data) {
            $('#sRes').css('display', 'block');
            if(data.answer == 'ok')
            {
            	$('#sRes').text('Теперь вы подписаны на рассылку.');
            }
            else if(data.answer == 'badEmail') 
            {
            	$('#sRes').text('Неверный адрес.');
            }
            else
            {
            	$('#sRes').text('Вы уже подписаны.');
            }
        }, 'json');
    	
    	return false;
    });
    $('#subscribe_only').focus(function(){
    	$('#subscribe_only').removeAttr('value');
    	return false;
    });
    
    $('a.modal').showModal();
});
$.fn.showModal = function(){
    this.each(function(){
        $(this).click(function(){
            $.showModal($(this).attr('href'), $(this).attr('title'));
            return false;
        })
    })
}

$.showModal = function(url, title) {
    var $popup = $('<div class="popup" id="popup"><div class="c"><div class="content"><h2></h2><div class="holder"><iframe class="frame"></iframe></div><a href="#" class="close">Закрыть</a></div></div><div class="b"></div></div>');
    $popup.find('.frame').height($(window).height() - 270).attr('src', url);
    //$popup.find('h2').text(title);

    var onResize = function() {
        $('#popup').find('.frame').height($(window).height() - 270);
    }
    $(window).bind('resize', onResize);

    var onUnblock = function() {
        $('#popup').remove();
        $(window).unbind('resize', onResize);
    }

    $.blockUI({
        'message': $popup,
        'css': {
            'cursor': 'normal',
            'background': 'none',
            'top': '0',
            'height': '100%',
            'width': '1042px',
            'left': ($(window).width() - 1042) / 2 + 'px',
            'border': 'none',
            'text-align': 'left'
        },
        'onUnblock': onUnblock
    });

    $popup.find('a.close').click(function(){
        $.unblockUI({
            'onUnblock': onUnblock
        });
        return false;
    });

    $('.blockOverlay').attr('title','Click to unblock').click(function(){
        $.unblockUI({
                'onUnblock': onUnblock
            })
    });
}
