window.onload = function() {
    $.loaded = {};
    $.loaded.cart = 0;
    $.loaded.ucp = 0;
    $.loaded.radio = 0

    var str_lang = $('span.lang').html();
    var path_root = '/';

    // basic css operations
    var margin_left = ($('body').width()-900)/2;
    $('#wrap').css('margin', '15px 0 0 '+margin_left+'px');
    $('body').css('background-position', $('body').width()+'px top');
    $(window).bind('resize', function() {
        var margin_left = ($('body').width()-900)/2;
        $('#wrap').css('margin', '15px 0 0 '+margin_left+'px');
        $('body').css('background-position', $('body').width()+'px top');
    });

    //
    // login/logout
    //
    $('#a_login').live('click', function(e) {
        var valid = 1;
        e.preventDefault();

        $('#form_login .error').remove();

        var $elm = $('#form_login .name');
        if ($($elm).val() == '') {
            $($elm).after('<span class="red error">&nbsp;'+$($elm).attr('errormsg')+'</span>');
            valid = 0;
        }

        var $elm = $('#form_login .password');
        if ($($elm).val() == '') {
            $($elm).after('<span class="red error">&nbsp;'+$($elm).attr('errormsg')+'</span>');
            valid = 0;
        }

        if (valid) {
            $('span.error').hide();
            login();
        }
    });

    $('#form_login input').live('keypress', function(e) {
        var key = (e.keyCode ? e.keyCode : e.which);
        if (key == 13) {
            login();
        }
    });

    $('#a_login_modal').live('click', function(e) {
        var valid = 1;
        e.preventDefault();

        $('#form_login_modal .error').remove();

        var $elm = $('#form_login_modal .name');
        if ($($elm).val() == '') {
            $($elm).after('<span class="red error">&nbsp;'+$($elm).attr('errormsg')+'</span>');
            valid = 0;
        }

        var $elm = $('#form_login_modal .password');
        if ($($elm).val() == '') {
            $($elm).after('<span class="red error">&nbsp;'+$($elm).attr('errormsg')+'</span>');
            valid = 0;
        }

        if (valid) {
            $('span.error').hide();
            login_modal();
            login();
        }
    });

    $('#form_login_modal input').live('keypress', function(e) {
        var key = (e.keyCode ? e.keyCode : e.which);
        if (key == 13) {
            login_modal();
            login();
        }
    });

    $('#a_logout').live('click', function() {
        url = $('#form_login').attr('action');
        $.post(url, {
            'logout': true
        }, function(html) {
            $('#container_login').html(html);
            $('#container_signup div').show();
            $('#a_account').hide();
        });
    });

    $('#a_trylogin').live('click', function() {
        url = $('#form_login').attr('action');
        $.post(url, {}, function(html) {
            $('#container_login').html(html);
        });
    });

    // go from menu to shop
    $('#menu .acc a').live('click', function(e) {
        e.preventDefault();
        $('#loader2').show().html($loader2());
        $.get($(this).attr('href'), {}, function(html) {
            load_new_page(html);        

            // products scrollable
            setTimeout(function() {
            	$("div#products_scrollable").scrollable({
            		vertical: true,
            		size: 2,
            		keyboard: false,
            		clickable: false
            	});
            	$('#loader2').hide();
            }, 510);
        });
    });

    // go back from shop to menu
    $('#a_goback').live('click', function() {
    	$('#loader2').show().html($loader2());
        $.get(path_root, {}, function(html) {
            load_new_page(html);
            setTimeout(function() {
            	initMenu();
            	$('#loader2').hide();
            }, 510);
        });
    });

    //
    // init product descriptions
    //
    var product_properties = new Array();
    product_properties[0] = 'caption';
    product_properties[1] = 'sku';
    product_properties[2] = 'isbn';
    product_properties[3] = 'availability';
    updateProductDescription($('div.product'), product_properties);

    var locked = 0;
    //
    // product lock/unlock
    //
    $('div.product').live('click', function() {
        updateProductDescription($(this), product_properties);
        // select a product
        if (!locked) {
            // stop hover, show caption
            $('div.product .over').each(function() {
                $(this).hide();
            });
            $('div.product .select').each(function() {
                $(this).hide();
            });
            $('.select', this).show();
            $(this).addClass('selected');

            // lock other products
            $('div.product').each(function() {
                if (!$(this).hasClass('hover')) {
                    $('.image', this).html('<img src="'+path_root+'themes/default/images/alpha_lock.png" />');
                }
            });
        // unlock products
        } else {
            // start hover
            $('div.product .over').each(function() {
                $(this).hide();
            });
            $('div.product .select').each(function() {
                $(this).hide();
            });
            $('.over', this).show();

            // unlock products
            $('div.product').each(function() {
                if (!$(this).hasClass('hover')) {
                    $('.image', this).html('&nbsp;');
                }
                if ($(this).hasClass('selected')) {
                    $(this).removeClass('selected');
                }
            });
        }
        locked = (locked+1)%2;
    });

    //
    // product hover
    //
    $('div.product').live('mouseover', function() {
        if (!locked) {
            $('div.product .over').each(function() {
                $(this).hide();
            });
            $('div.product .select').each(function() {
                $(this).hide();
            });
            $('.over', this).show();
            updateProductDescription($(this), product_properties);
        }

        if (!locked || $(this).hasClass('selected')) {
            $(this).addClass('hover');
        }
    });
    $('div.product').live('mouseout',  function() {
        $(this).removeClass('hover');
    });

    //
    // select product attributes
    //
    $('#right .container2 .attributes p.options span').live('click', function() {
        $('span', this.parentNode).each(function() {
            if ($(this).hasClass('selected')) {
                $(this).removeClass('selected')
            }
        });
        $(this).addClass('selected');
    });

    //
    // add product to cart
    //
    $('#a_cart_add_product').live('click', function() {
        var url_cart_submit = $('#url_cart_submit').attr('href');
        var id = $(this).attr('rel');
        var caption = $('#right .product_caption').html();
        var attributes_ok = true;
        var attribute_names = '';
        var attributes = '';

        $('#right .container2 .attributes > div').each(function() {
            if ($('.caption', this).html() && !$('.selected', this).size()) {
                attributes_ok = false;
                if (attribute_names) {
                    if (str_lang == 'gr') {
                        attribute_names = attribute_names + ' και ';
                    } else {
                        attribute_names = attribute_names + ' and ';
                    }
                }
                attribute_names = attribute_names+'"'+$('.caption', this).html().toLowerCase()+'"';
            } else {
                if ($('.selected', this).html()) {
                    var id = $('.id', this).html();
                    attributes = attributes+id+':'+$('.selected', this).html()+';';
                }
            }
        });

        var availability = $('#right .product_availability a').html();
        if ((availability==2) || (availability==100)) {
                if (str_lang == 'gr') {
                    alert('Το προϊόν "'+$('#right .product_caption').html()+'" είναι εκτός στοκ.');
                } else {
                    alert('Product "'+$('#right .product_caption').html()+'" is out of stock.');
                }
            
            return false;
        }

        if (attributes_ok) {
            $.post(url_cart_submit, {
                "add" : id,
                "attributes" : attributes
            }, function() {
                if (str_lang == 'gr') {
                    alert('Το προϊόν "'+$('#right .product_caption').html()+'" προστέθηκε στο καλάθι.');
                } else {
                    alert('Product "'+$('#right .product_caption').html()+'" was added to cart.');
                }
            });
        } else {
            if (str_lang == 'gr') {
                alert('Πρέπει να διαλέξεις '+attribute_names+' πριν βάλεις το προϊόν στο καλάθι.');
            } else {
                alert('You must select '+attribute_names+' before adding this product to cart.');
            }
        }

        return false;
    });

    //
    // update cart
    //
    $('#a_cart_update').live('click', function(e) {
        e.preventDefault();
        var form = $('#form_cart_update');

        $('#a_cart_update_fire').attr('href', $(this).attr('href')+'?'+$(form).serialize()+'&modal=true');
        $('#a_cart_update_fire').click();
    });

    //
    // close thickbox
    //
    $(document).live('keypress', function(e) {
        if (e.keyCode==27) {
            self.tb_remove();
        }
    });
    
    $('#TB_overlay').live('click', function() {
        self.tb_remove();
    });

//
// Extend form validator
//
	// password confirm
	$.validator.addMethod("passwordConfirm", function(value) {
		return value == $('#password').val();
	}, 'Passwords do not match');

	// mail confirm
	$.validator.addMethod("emailConfirm", function(value) {
		return value == $('#email').val();
	}, 'E-mails do not match');

	// human confirm
	$.validator.addMethod("humanConfirm", function(value) {
		return value == 5;
	}, 'Answer is 5');

    // init menu
    var menu_enabled = 1;
    $('#menu ul li h3').live('mouseover', function() {
        if (!$('.acc-section', this.parentNode).hasClass('active')) {
            $('#menu .active').removeClass('active').hide('slow');
            if ($('a', this.parentNode).size()) {
                $('.acc-section', this.parentNode).addClass('active').show('slow');
            }
        }
        menu_enabled = 0;
        setTimeout(function() {menu_enabled = 1;}, 30);
    });

	$('#loader').hide();
	$('#wrapper').show('slow');
	initMenu();

//	setTimeout('googleAnalytics()', 5000);
}


var updateProductDescription = function(prdct, product_properties) {
    // "static" properties
    for (i in product_properties) {
        $('#right .product_'+product_properties[i]).html($('.properties .'+product_properties[i], prdct).html());
    }

    // specs + tooltip
    $('#right .product_specs').attr('tooltip', $('.properties .description', prdct).html());
    $('#right .product_specs').html($('.properties .specs', prdct).html());

    // price
    var price = $('.properties .price', prdct).html();
    var discount = $('.properties .discount', prdct).html();
    if (discount!=0) {
        price = '<span class="grey strikeout">'+price+'&euro;</span> '+(price*(100-discount)/100)+'&euro;';
    } else {
        price = price+'&euro;';
    }
    $('#right .product_price').html(price);

    // product attributes
    $('#right .attributes').html('');
    var i = 0;
    $('.attributes', prdct).each(function() {
        if (i<2) {
            var caption = $('.caption', this).html();
            var options = $('.options', this).html();
            var id = $('.attr_id', this).html();

            $('#right .attributes').append('<div>'+
                                           '    <div class="cufon_db grey">'+caption+'&nbsp;</div>'+
                                           '    <p class="options">'+options+'&nbsp;</p>'+
                                           '    <p class="caption" style="display:none;">'+caption+'</p>'+
                                           '    <p class="id" style="display:none;">'+id+'</span>'+
                                           '</div>'+
                                           '<br clear="all" />');
            i = i+1;
        }
    });
    while (i<2) {
        $('#right .attributes').append('<div class="cufon_db">&nbsp;</div>'+
                                       '<p>&nbsp;</p>'+
                                       '<br clear="all" />');
        i = i+1;
    }

    // gallery
    $('#right .moreviews').remove();
    $('#right .gallery').each(function() {
        $(this).hide();
    });

    $('#right .gallery[rel='+$('.id', prdct).html()+']').show();

    // add to cart link
    $('#a_cart_add_product').attr('rel', $('.id', prdct).html());

    // refresh fonts
    Cufon.refresh();
}

var load_new_page = function (html) {
    $('#wrapper').hide(500);
    setTimeout(function() {
        $('#wrapper').html(html);
        $('#wrapper').show(500);
    }, 500);
    setTimeout(function() {
        Cufon.refresh();
        initTooltips();
    }, 510);
}

var login = function() {
    url = $('#form_login').attr('action');
    name = $('#form_login .name').val();
    password = $('#form_login .password').val();
    $.post(url, {
        'name': name,
        'password' : password
    }, function(html) {
        $('#container_login').html(html);

        if (parseInt($('#container_login #session_logged_in').html())) {
            // hide signup
            $('#container_signup div').hide();
            // show account edit
            $('#a_account').show();
        }
    });
}

var login_modal = function() {
    var url = $('#form_login_modal').attr('action');
    var name = $('#form_login_modal .name').val();
    var password = $('#form_login_modal .password').val();
    var container = $(this).parent();

    $.post(url, {
        'name': name,
        'password' : password
    }, function(html) {
        $('#TB_ajaxContent').html(html);
    });
}

var initMenu = function() {
// jquery ui
/*
    $("#accordion").accordion({
      "header": 'h3',
      "autoHeight": true,
      "event": 'mouseover'
    });
 */

// leigeber
/*
	var parentAccordion=new TINY.accordion.slider("parentAccordion");
	parentAccordion.init("acc", "h3", 1);
 */

// custom
    $('#menu .acc-section').each(function() {
        if ($(this).is(':visible')) {
            $(this).hide();
        }
    });
}

var initTooltips = function (where) {
    $('[tooltip]', where).tooltip({
        bodyHandler: function() {
            return $(this).attr('tooltip');;
        },
        delay: 0,
        track: false,
        showURL: false
    });
}

var change_address = function(str_address_select, str_target) {
    $address_select = $(str_address_select);
    $target = $(str_target);

	var val = $($address_select).attr("value");
	if (val != '') {
		$($target).html($('div.'+val).html());
		$('label', $target).each(function() {
		    $(this).addClass('cufon_db').addClass('grey');
		});
		Cufon.refresh();
	}

    return true;
}

var $loader2 = function() {
	return $('<img />').attr('src', $('#loader2 > img').attr('src'));
}

/*
var googleAnalytics = function() {
	var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
	document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));

	try {
	var pageTracker = _gat._getTracker("UA-320181-5");
	pageTracker._trackPageview();
	} catch(err) {}
}
*/
