﻿function rString() {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = 8;
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}

function	flashItem(objid, duration)
{
		$(objid).animate( {opacity: 0.0}, duration/2, function()
		{
			$(this).animate( {opacity: 1.0}, duration/2);
		});
}

var totalprice = 0;

function	recalc_order(amount)
{
	totalprice	=   +totalprice;				// convert to number before operation
	totalprice +=   +amount;                	// add passed parameter
	totalprice 	=   (+totalprice).toFixed(2);   // convert back to formatted string of precision 2
	if(0 == +totalprice)
	{
		$('#cart_empty')
			.text('ΜΕΧΡΙ ΣΤΙΓΜΗΣ ΔΕΝ ΕΧΕΤΕ ΠΡΟΣΘΕΣΕΙ ΚΑΠΟΙΟ ΑΝΤΙΚΕΙΜΕΝΟ ΣΤΗΝ ΠΑΡΑΓΓΕΛΙΑ ΣΑΣ')
			.animate( {opacity: 1.0}, 200);
		$('#cart_list').addClass('hide');
	}
	else
	{
		$('#cart_empty').text('ΓΙΑ ΝΑ ΟΛΟΚΛΗΡΩΣΕΤΕ ΤΗΝ ΑΓΟΡΑ ΣΥΜΠΛΗΡΩΣΤΕ ΤΗΝ ΦΟΡΜΑ ΜΕ ΤΑ ΣΤΟΙΧΕΙΑ ΣΑΣ ΣΤΟ ΤΕΛΟΣ ΤΗΣ ΣΕΛΙΔΑΣ.');
		$('#cart_list').removeClass('hide');
	};

	$('#cart_finalprice').text('ΣΥΝΟΛΟ ΑΓΟΡΩΝ (Συμπεριλαμβάνει ΦΠΑ): '+totalprice+' ευρώ');
	flashItem('#cart_finalprice', 800);

	$('#fproductlist').val( $('#orderlist').text() );

};
function	remove_item(x,price)
{
  	$('#'+x).remove();
	$('#'+x+'_ol').remove();
	recalc_order(-price);
};

function add_item(x,price,notifyok)
{
	var itemname = 'ulitem_'+rString();
	var itemnameol = itemname+'_ol';
	$('#cart_list')
		.append('<li id="'+itemname+'">'+x+'('+price+'€)[<a onclick="javascript:remove_item(\''+itemname+'\','+price+')">ΔΙΑΓΡΑΦΗ</a>]</li>')
		.find('li:last')
		.hide()
		.fadeIn(500);
		
	$('#orderlist')
		.append('<li id="'+itemnameol+'">('+price+'€) '+x+' #</li>')
		.find('li:last')
		.hide()
		.fadeIn(500);
	
	$('#'+notifyok)
		.css('display','block')
		.html('OK! (Η προσθήκη έγινε στο καλάθι αγορών. Μπορείτε να δείτε τα περιεχόμενα του καλαθιού σας στα δεξιά αυτής της σελίδας. <strong>Κάντε scroll πάνω ή κάτω εάν δεν φαίνεται!</strong>)');
	flashItem('#'+notifyok, 800);
	recalc_order(price);
};

function	validate_formfields()
{
	var nameOK = 0;
	var name2OK = 0;
	var	cityOK = 0;
	var streetOK = 0;
	var postalOK = 0;
	var phoneOK = 0;
	
	var displayValidation = function(fieldID, success)
	{
		if(typeof success == 'undefined')
			success = 0;
		if(success)
		{
			$(fieldID)
				.removeClass('error')
				.addClass('success')
				.html('OK!');
		}
		else
		{
			$(fieldID)
				.removeClass('success')
				.addClass('error')
				.html('X');
		}
	};

	/* check if all fiends are ok */
	var tstr = $('#name').val();
	if( tstr.length >= 1 )
	{
		nameOK = 1;
		displayValidation('#validateNameOK', 1);
	} else {nameOK = 0;displayValidation('#validateNameOK', 0);};

	var tstr = $('#name2').val();
	if( tstr.length >= 1 )
	{
		name2OK = 1;
		displayValidation('#validateName2OK', 1);
	} else {nameOK = 0;$('#validateName2OK').html('<span style="color:red;"> X </span>');};

	var tstr = $('#city').val();
	if( tstr.length >= 1 )
	{
		cityOK = 1;
		displayValidation('#validateCityOK', 1);
	} else {nameOK = 0;displayValidation('#validateCityOK', 0);};

	var tstr = $('#street').val();
	if( tstr.length >= 1 )
	{
		streetOK = 1;
		displayValidation('#validateStreetOK', 1);
	} else {nameOK = 0;displayValidation('#validateStreetOK', 0);};

	var tstr = $('#postal').val();
	if( tstr.length >= 1 )
	{
		postalOK = 1;
		displayValidation('#validatePostalOK', 1);
	} else {nameOK = 0;displayValidation('#validatePostalOK', 0);};

	var tstr = $('#phone').val();
	if( tstr.length >= 10 )
	{
		phoneOK = 1;
		displayValidation('#validatePhoneOK', 1);
	} else {nameOK = 0;displayValidation('#validatePhoneOK', 0);};

	if( nameOK && name2OK && cityOK && streetOK && postalOK && phoneOK )
	{
		$('#orderbtn').removeAttr("disabled");
	}
	else
	{
		$('#orderbtn').attr('disabled','disabled');
	};
};

// variables
var img_imgURL			=	'http://www.stopit.gr/shoppics',
	img_bigImgURL       =   img_imgURL+'/xl/',
    img_mediumImgURL    =   img_imgURL+'/m/',
    img_smallImgURL     =   img_imgURL+'/s/',
    img_arrPImages      =   {},
    img_primaryAff      =   'primary_',
    img_thumbnailAff    =   'thumbnail_',
    img_imageAff        =   'image_',
	prettyPhotoConfig   =					// prettyPhoto Configuration
	{
		animationSpeed:'normal',
		allowresize:true,
		autoplay:true,
		counter_separator_label:'/',
		default_width:500,
		default_height:344,
		deeplinking:false,
		hideflash:true,
		ie6_fallback: true,
		keyboard_shortcuts: false,
		modal:false,
		opacity:0.50,
		overlay_gallery: false,
		showTitle: false,
		social_tools: false,
		theme:'light_rounded',
		wmode:'opaque'
	};

// DOM selectors
var desc_FullContentBtnId	=   '.c_shop_item_showFullContentBtn',
    desc_FullContentId		=   '.c_shop_item_fullContent',
	desc_FullContentBtn,
	desc_FullContent,
    img_ProductImgs         =   '.c_shop_item_images',
    img_PrimaryImg          =   '.c_shop_item_image',
    img_Thumbnails          =   '.c_shop_item_thumbnails',
    img_Thumbnail           =   '.c_shop_item_thumbnail';

// functions
function cacheDOMIDs()
{
    desc_FullContentBtn     =   $(desc_FullContentBtnId);
    desc_FullContent        =   $(desc_FullContentId);
}

function fullContent()
{
    var show = function(content, contentBtn)
    {
        contentBtn
            .find('span')
            .removeClass()
            .addClass('expanded')
            .data('btnTxt', contentBtn.find('span').text())
            .text('hide full content');
        content
            .after(contentBtn)
            .slideDown(500)
			.css('display', 'block');
    };
    var hide = function(content, contentBtn)
    {
        contentBtn
            .find('span')
            .removeClass()
            .addClass('collapsed')
            .text(contentBtn.find('span').data('btnTxt'));
        content.slideUp(500, function()
        {
            $(this)
				.before(contentBtn)
				.css('display', 'none');
        });
    };
    desc_FullContentBtn.click(function(e)
    {
        e.preventDefault();
        if($(this).find('span').hasClass('expanded'))
        {
            hide($(desc_FullContent[desc_FullContentBtn.index($(this))]), $(this));
        }
        else
        {
            show($(desc_FullContent[desc_FullContentBtn.index($(this))]), $(this));
        }
    });
}

function imagerInit()
{
    $(img_ProductImgs).each(function()
    {
        var productID       =   $(this).attr('id').split('_')[1],
            primaryImgID    =   $(this).find(img_PrimaryImg).attr('id').split('_')[1],
            thumbnails      =   $(this).find(img_Thumbnails);
			
        img_arrPImages[productID]   =   {'primary' : primaryImgID};
		
        thumbnails.each(function()
        {
            var thumbIDs	=	$(this).find(img_Thumbnail);
            thumbIDs.each(function()
            {
                var thumbID		=	$(this).attr('id').split('_')[1],		
					img 		=	$(this).find('img');
			
                if(thumbID == primaryImgID)
				{
                    img.addClass('active');
                }

                img.click(function()
                {
                    var id  =   $(this).attr('id').split('_'),
                        iID =   id[1], // image id
                        pID =   id[2]; // product id
                    if(iID != img_arrPImages[pID]['primary'])
                    {
                        var thumbFilename   =   ($('#'+img_imageAff+iID+'_'+pID).attr('src')).split('/'),
							mainImg			=	new Image();

                        thumbFilename   =   (thumbFilename[thumbFilename.length-1]).split('_')[2];  // get filename
						$('#'+img_primaryAff+img_arrPImages[pID]['primary']+'_'+pID)
							.removeClass('c_shop_item_image')
							.addClass('c_shop_item_image_loading')
							.find('a')
							.html('');
						setTimeout(function(){
						$(mainImg)
							.load(function()
							{
								$(this).css('display', 'none');
								
								$('#'+img_primaryAff+img_arrPImages[pID]['primary']+'_'+pID)
									.attr('id', img_primaryAff+iID+'_'+pID)
									.removeClass('c_shop_item_image_loading')
									.addClass('c_shop_item_image')
									.find('a')
									.attr('href', img_bigImgURL+pID+'_big_'+thumbFilename)
									.html(this);
								$(this).fadeIn(500);

								$('#'+img_imageAff+img_arrPImages[pID]['primary']+'_'+pID).removeClass('active');
								$('#'+img_imageAff+iID+'_'+pID).addClass('active');
								
								img_arrPImages[pID]['primary'] = iID;		// save image id
							})
							.attr('src', img_mediumImgURL+pID+'_image_'+thumbFilename);
						}, 500);
                    }
                });
            });
        });
    });
}

function shopInit()
{
	cacheDOMIDs();
    fullContent();
    imagerInit();
	$("a[rel^='prettyPhoto']").prettyPhoto(prettyPhotoConfig);
}

function shopReinit() // used on ajax loads
{
	cacheDOMIDs();
    fullContent();
    imagerInit();
	$("a[rel^='prettyPhoto']").prettyPhoto(prettyPhotoConfig);
}

$(document).ready(function(){
    shopInit();
});

