// Variable to hold auction data
    var auctions = '';
    var auctionObjects = new Array();
	var getstatus_url_time;
    var getstatus_url;
	var bidBalance;
	var bidOfficialTime;
    var bidBalance;

function convertToNumber(sourceString){
	return sourceString.replace(/&#[0-9]{1,};/gi, "")
					   .replace(/&[a-z]{1,};/gi, "")
					   .replace(/[a-zA-Z]+/gi, "")
					   .replace(/[^0-9\,\.]/gi, "");
}

$(document).ready(function(){

	if ($('#login-but').length > 0) {
		$('#container').bind('click', function () {
			if ($('#login-but').hasClass('login-showed')) {
				$('#login-but').trigger('click');
			}
		});
		$('.footer').bind('click', function () {
			if ($('#login-but').hasClass('login-showed')) {
				$('#login-but').trigger('click');
			}
		});
	}

    // Collecting auction data, the layer id and auction id
    $('.auction-item').each(function(){
        var auctionId    = $(this).attr('id');
        var auctionTitle = $(this).attr('title');
		
        if($('#' + auctionId + ' .countdown').length){
            // collect the id for post data
            auctions = auctions + auctionId + '=' + auctionTitle + '&';

            // collect the object
            auctionObjects[auctionId]                           = $('#' + auctionId);
            auctionObjects[auctionId]['flash-elements']         = $('#' + auctionId + ' .countdown, #' + auctionId + ' .bid-price, #' + auctionId + ' .bid-bidder, #' + auctionId+ ' .bid-savings-price, #' + auctionId + ' .bid-savings-percentage, #' + auctionId + ' .closes-on');
            auctionObjects[auctionId]['countdown']              = $('#' + auctionId + ' .countdown');
            auctionObjects[auctionId]['closes-on']              = $('#' + auctionId + ' .closes-on');
            auctionObjects[auctionId]['bid-bidder']             = $('#' + auctionId + ' .bid-bidder');
            auctionObjects[auctionId]['bid-button']             = $('#' + auctionId + ' .bid-button');
            auctionObjects[auctionId]['bid-button-a']           = $('#' + auctionId + ' .bid-button a');
            auctionObjects[auctionId]['bid-button-p']           = $('#' + auctionId + ' .bid-button p');
            auctionObjects[auctionId]['bid-price']              = $('#' + auctionId + ' .bid-price');
            auctionObjects[auctionId]['bid-price-fixed']        = $('#' + auctionId + ' .bid-price-fixed');
            auctionObjects[auctionId]['bid-loading']            = $('#' + auctionId + ' .bid-loading');
            auctionObjects[auctionId]['bid-message']            = $('#' + auctionId + ' .bid-message');
            auctionObjects[auctionId]['bid-flash']              = $('#' + auctionId + ' .bid-flash');
            auctionObjects[auctionId]['bid-savings-price']      = $('#' + auctionId + ' .bid-savings-price');
            auctionObjects[auctionId]['bid-savings-percentage'] = $('#' + auctionId + ' .bid-savings-percentage');
            auctionObjects[auctionId]['bid-bookbidbutler']      = $('#' + auctionId + ' .bid-bookbidbutler');
			auctionObjects[auctionId]['bid-price-increment']    = $('#' + auctionId + ' .bid-price-increment');
			auctionObjects[auctionId]['bid-time-increment']     = $('#' + auctionId + ' .bid-time-increment');
            auctionObjects[auctionId]['bid-histories']          = $('#bidHistoryTable' + auctionTitle);
            auctionObjects[auctionId]['bid-histories-p']        = $('#bidHistoryTable' + auctionTitle + ' p');
            auctionObjects[auctionId]['bid-histories-tbody']    = $('#bidHistoryTable' + auctionTitle + ' tbody');
        }
    });

    // additional object
    var price                  = '';
    var priceFixed             = '';

    if($('.bid-histories').length){
        getstatus_url = '?histories=yes';
    }else{
        getstatus_url = '';
    }

    function convertToNumber(sourceString){
        return sourceString.replace(/&#[0-9]{1,};/gi, "")
                            .replace(/&[a-z]{1,};/gi, "")
                            .replace(/[a-zA-Z]+/gi, "")
                            .replace(/[^0-9\,\.]/gi, "");
    }

    // Do the loop when auction available only
    if (auctions && typeof(curr_page_type) === 'undefined') {
        setTimeout(getAuctionStatus, 1000);
    } else {
		if ($('#serv_time').length > 0) {
			setInterval(show_time, 1000);
		}
	}
	
	if ($('.bid-balance').length > 0) {
		show_bid_balance();
		setInterval(show_bid_balance, 10000);
	}

    // Function for bidding
    $('.bid-button-link').click(function(){
        var auctionElement = 'auction_' + $(this).attr('title');

        auctionObjects[auctionElement]['bid-button'].hide(1);
        auctionObjects[auctionElement]['bid-loading'].show(1);

        $.ajax({
            url: $(this).attr('href'),
			cache: false,
            dataType: 'json',
            success: function(data){
                auctionObjects[auctionElement]['bid-message'].html(data.Auction.message)
                                                             .fadeIn(1000)
															 .fadeOut(5000);

                auctionObjects[auctionElement]['bid-button'].show(1);
                auctionObjects[auctionElement]['bid-loading'].hide(1);
            }
        });

        return false;
    });

// Function for adding auction into the watchlist
    $('.auction-button-link').click(function(){
        var auctionElement = $(this).attr('title');

        $(this).hide();
		$(this).after('<img id="loader_'+auctionElement+'" src="/img/ajax-loader2.gif" style="margin-top:12px;"/>')
		
		
        $.ajax({
            url: $(this).attr('href'),
			cache : false,
            dataType: 'json',
            success: function(data){
                auctionObjects['auction_'+auctionElement]['bid-message'].html(data.message)
                                                                        .fadeIn(1000)
																		.fadeOut(5000);
				if  (data.flag == 1) {
					$('#watch_'+auctionElement).text('Remove From Watchlist');
					pre_href = $('#watch_'+auctionElement).attr('href');
					new_href = pre_href.replace(/add_ajax\/.*$/, 'delete_ajax/'+data.nid);
					$('#watch_'+auctionElement).attr('href', new_href);
				}
				
				if  (data.flag == 3) {
					$('#watch_'+auctionElement).text('Add to Watchlist');
					pre_href = $('#watch_'+auctionElement).attr('href');
					new_href = pre_href.replace(/delete_ajax\/.*$/, 'add_ajax/'+data.aid);
					$('#watch_'+auctionElement).attr('href', new_href);
				}
				$('#loader_'+auctionElement).remove();
				$('#watch_'+auctionElement).show();
            }
        });

        return false;
    });
	
    // Function to check limit and change the icon whenever it's changed
    // Run only when bid icon available
    if($('.bid-limit-icon').length){
        setInterval(function(){
            var count = $('.bid-limit-icon').length
            if(count > 0){
                $.ajax({
                    url: '/limits/getlimitsstatus/?ms=' + new Date().getTime(),
                    dataType: 'json',
                    success: function(data){
                        if(data){
                            $('.bid-limit-icon').each(function(i){
                                if(data[i].image){
                                    $(this).attr('src', '/img/'+data[i].image);
                                }
                            });
                        }
                    }
                });
            }
        }, 30000);
    }

    if($('.productImageThumb').length){
        $('.productImageThumb').click(function(){
            $('.productImageMax').fadeOut('fast').attr('src', $(this).attr('href')).fadeIn('fast');
            return false;
        });
    }

    if($('#CategoryId').length){
        $('#CategoryId').change(function(){
            document.location = '/categories/view/' + $('#CategoryId option:selected').attr('value');
        });
    }

    if($('#myselectbox').length){
        $('#myselectbox').change(function(){
            document.location = '/categories/view/' + $('#myselectbox option:selected').attr('value');
        });
    }
	
	$('#login-but').bind('click', toggleLogin);
	$('.login-bid-but').hover(
		function () {
			$(this).children('input').attr('value', 'Login');
		},
		function () {
			$(this).children('input').attr('value', 'Bid Now');
		}
	);
	
	$('.close').bind('click', function () {
		$(this).closest('.alertBox').fadeOut(1000);
	});
	
	if ($('.alertBox').length > 0) {
		setTimeout(hideAlerts, 25000);
	}
	
	// additional object
    bidOfficialTime        = $('.bid-official-time');
    bidBalance             = $('.bid-balance');
	
	// Lazyload after page loaded 
	setTimeout(lazy_load, 5000);
});

function hideAlerts()
{
	$('.alertBox').fadeOut(1000);
}

function toggleLogin()
{
	if ($(this).hasClass('login-showed')) {
		$('#panel').animate({'top' : '-270px'}, '1000', function () {
			$('#panel').css({'z-index':''});
		});
		hgt = '69px';
		if ($.browser.msie && $.browser.version <= 6) {
			hgt = '70px';
		}
		$('#topNavDiv').animate({'top':'0px'}, '950', function () {
			$('#tabs_cont').css({'margin-top':hgt});
			$('#topNavDiv').css({'position':'', 'z-index':''});
		});
		$(this).text('Login');
		$(this).removeClass('login-showed');
	} else {
		$('#tabs_cont').css({'margin-top':'105px'});
		$('#topNavDiv').css({'position':'absolute', 'z-index':'9999'});
		$('#panel').css({'z-index':'9999', 'left':'0px'});
		$('#panel').animate({'top' : '0px'}, '1000');
		$('#topNavDiv').animate({'top':'266px'}, '1000');
		$(this).text('Close');
		$(this).addClass('login-showed');
	}
	return false;
}

var bot = 0;

function getAuctionStatus()
{
	switch (bot) {
		case 0:
			getstatus_url2 = '/gutter.html'+getstatus_url;
			bot++;
			break;
			
		case 1:
			getstatus_url2 = '/gutter.html'+getstatus_url;
			bot++;
			break;
			
		case 2:
			getstatus_url2 = '/gutter.html'+getstatus_url;
			bot = 0;
			break;
			
	}
	getstatus_url_time = getstatus_url2;
	$.ajax({
		url: getstatus_url_time,
		dataType: 'json',
		type: 'get',
		cache: false,
		data: auctions,
		success: setAuctionStatus,
		error: function(XMLHttpRequest, textStatus, errorThrown){
			// On error send request after 5 second
			setTimeout(getAuctionStatus, 5000);
		}
	});
}

k = 0;
got_data = false;
function setAuctionStatus(data)
{

	if(data[0]) {
		if(data[0].Auction.serverTimeString) {
			if(bidOfficialTime.html()) {
				bidOfficialTime.html(data[0].Auction.serverTimeString);
			}
		}
		/*if(data[0].Balance) {
			if(bidBalance.html()) {
				if (data[0].Balance.balance == '') {
					data[0].Balance.balance = 0;
				}
				bidBalance.html(data[0].Balance.balance);
			}
		}*/
	}
	
	$.each(data, function(i, item){
	
		if (typeof auctionObjects[item.Auction.element] == 'undefined') {
			return;
		}
	
		if (typeof auctionObjects[item.Auction.element]['bid-price-fixed'] == 'undefined') {
			return;
		}
	
		if(auctionObjects[item.Auction.element]['bid-price-fixed'].html()){

			if(auctionObjects[item.Auction.element]['bid-price-fixed'].length > 1) {
				auctionObjects[item.Auction.element]['bid-price-fixed'].each(function(){
					price = $(this).html();
				});
			} else {
				price = auctionObjects[item.Auction.element]['bid-price-fixed'].html();
			}

		} else {

			if (auctionObjects[item.Auction.element]['bid-price'].length > 1) {
				auctionObjects[item.Auction.element]['bid-price'].each(function() {
					price = $(this).html();
				});
			} else {
				price = auctionObjects[item.Auction.element]['bid-price'].html();
			}

		}

		price = price.replace(/<span class=(")*rp(")*[^>]+>.*<\/span>/i, '');
		price = convertToNumber(price);
		if (price == '.0') {
			price = '0';
		}
		if (auctionObjects[item.Auction.element]['bid-bidder'].html() != item.LastBid.username) {
			auctionObjects[item.Auction.element]['bid-bidder'].html(item.LastBid.username);
		}
		
		if (item.settingIncrement) {
			auctionObjects[item.Auction.element]['bid-price-increment'].html(item.settingIncrement.price_increment);
			auctionObjects[item.Auction.element]['bid-time-increment'].html(item.settingIncrement.time_increment);
		}
		
		hlgt = false;
		
		item.Auction.price = item.Auction.price.replace(/(INR|Rs. )/, '<span class="rp">`</span> ');
		
		if (price != convertToNumber(item.Auction.price)) {
			hlgt = true;
			g = convertToNumber(item.Auction.price)

			if (item.Auction.price == '0' || item.Auction.price == 'Rs. 0' || g == '0') {
				item.Auction.price = '<span class="rp">`</span> 0';
			}
			auctionObjects[item.Auction.element]['bid-price'].html(item.Auction.price);
			auctionObjects[item.Auction.element]['bid-price-fixed'].html(item.Auction.price);

			if (auctionObjects[item.Auction.element]['bid-flash'] && item.Message) {
				auctionObjects[item.Auction.element]['bid-flash'].html(item.Message.message).show(1).animate({opacity: 1.0}, 2000).hide(1);
			}

			if (auctionObjects[item.Auction.element]['bid-histories'].length) {
				if(auctionObjects[item.Auction.element]['bid-histories-p'].html()) {
					auctionObjects[item.Auction.element]['bid-histories-p'].remove();
				}

				auctionObjects[item.Auction.element]['bid-histories-tbody'].empty();

				ei = 0;
                $.each(item.Histories, function(n, tRow) {
					cclass = '';
					if (ei % 2 == 0) {
						cclass = 'class="alt"';
					}
					var row = '<tr '+cclass+'><td>' + tRow.Bid.created + '</td><td>' + tRow.User.username + '</td><!--<td>' + tRow.Bid.description + '</td>--></tr>';

					auctionObjects[item.Auction.element]['bid-histories-tbody'].append(row);
					ei++;
				});

				auctionObjects[item.Auction.element]['closes-on'].html(item.Auction.closes_on);
				auctionObjects[item.Auction.element]['bid-savings-percentage'].html(item.Auction.savings.percentage);
				item.Auction.savings.price = item.Auction.savings.price.replace(/(INR|Rs. )/, '<span class="rp">`</span> ');
				auctionObjects[item.Auction.element]['bid-savings-price'].html(item.Auction.savings.price);
			}

			//auctionObjects[item.Auction.element]['flash-elements'].effect("highlight", {}, 1500);
			auctionObjects[item.Auction.element]['flash-elements'].hide();
			auctionObjects[item.Auction.element]['flash-elements'].css({'backgroundColor':'#fff680'});
			auctionObjects[item.Auction.element]['flash-elements'].fadeIn(500, function () {
				$(this).css({'backgroundColor' : ''});
			});
		} else {
			if (item.Auction.price == '0') {
				auctionObjects[item.Auction.element]['bid-price'].html('<span class="rp">`</span> 0');
			}
		}

		auctionObjects[item.Auction.element]['jpeak_only'] = item.Auction.peak_only;
		auctionObjects[item.Auction.element]['jisPeakNow'] = item.Auction.isPeakNow;
		auctionObjects[item.Auction.element]['jend_time'] = item.Auction.end_time;
		auctionObjects[item.Auction.element]['jserverTimestamp'] = item.Auction.serverTimestamp;
		auctionObjects[item.Auction.element]['jtime_left'] = item.Auction.time_left;
		auctionObjects[item.Auction.element]['jclosed'] = item.Auction.closed;
		auctionObjects[item.Auction.element]['jstart_time_status'] = item.Auction.start_time_status;
		
		if (item.Auction.peak_only == 1 && item.Auction.start_time_status != 4) {
			
			st = 'Coming Soon';
			switch (item.Auction.start_time_status) {
				case 0:
					st = 'Coming Soon';
					break;
					
				case 1:
					st = 'Resumes '+item.Auction.peak_start_time;
					break;
					
				case 2:
					if (item.Auction.isPeakNow) {
						st = 'Opens Today '+item.Auction.start_time_hr;
					} else {
						st = 'Opens Today '+item.Auction.peak_start_time;
					}
					break;
					
				case 3: 
					st = 'Paused';
					break;
					
				//This should never come here
				case 4:
					break;
					
				case 5:
					st = 'Checking...';
					break;
			}
			auctionObjects[item.Auction.element]['countdown'].html(st);
			auctionObjects[item.Auction.element]['countdown'].removeAttr('style');
			
			if (item.Auction.start_time_status < 4) {
				auctionObjects[item.Auction.element]['bid-button-a'].hide();
			}
			if (auctionObjects[item.Auction.element]['bid-button-p'].html() == '') {
				auctionObjects[item.Auction.element]['bid-button'].append('<p>Peak Only Auction</p>');
			}
		} else {
			if (hlgt) {
				if (item.Auction.end_time - item.Auction.serverTimestamp > 0) {
					auctionObjects[item.Auction.element]['countdown'].html(item.Auction.end_time_string);
				
					if (item.Auction.time_left <= 10) {
						auctionObjects[item.Auction.element]['countdown'].css({'color': '#ffffff', 'background-color':'#ff0000', 'padding-left':'2px', 'padding-right':'2px'});
					} else {
						auctionObjects[item.Auction.element]['countdown'].removeAttr('style');
					}
				} else {
					if (item.Auction.end_time - item.Auction.serverTimestamp < -5) {
						auctionObjects[item.Auction.element]['countdown'].removeAttr('style');
						auctionObjects[item.Auction.element]['countdown'].html('checking...');
					}
				}
			}

			if (auctionObjects[item.Auction.element]['bid-button-p'].html()) {
				auctionObjects[item.Auction.element]['bid-button-a'].show();
				auctionObjects[item.Auction.element]['bid-button-p'].remove();
			}
		}

		if (item.Auction.time_left < 1 && item.Auction.closed == 1) {
			auctionObjects[item.Auction.element]['countdown'].removeAttr('style');
			auctionObjects[item.Auction.element]['countdown'].html('Closed');
			auctionObjects[item.Auction.element]['bid-button'].hide();
			auctionObjects[item.Auction.element]['bid-bookbidbutler'].hide();
		}
		

			var dy = item.Auction.time_diff['day'];
			var hr = item.Auction.time_diff['hour'];
			var mins = item.Auction.time_diff['min'];
			var sec = item.Auction.time_diff['sec'];
			var d = new Date();
			d.setHours(hr);
			d.setMinutes(mins);
			d.setSeconds(sec);
			mine = d.getTime();
			auctionObjects[item.Auction.element]['time_d_day'] = dy;
			auctionObjects[item.Auction.element]['time_d'] = mine;

	});
	
	if (!got_data) {
		setInterval(ctimer, 1000);
	}
	if (typeof Cufon != 'undefined') {
		Cufon.replace('span.rp');
	}
	got_data = true;
	setTimeout(getAuctionStatus, 1000);
}

function lazy_load()
{
	$.getScript('/js/jquery.tweet.js', function() {
		$(".tweet").text('');
		jQuery(document).ready(function($) {

       $(".tweet").tweet({
         join_text: "auto",
         username: "bidjeeto",
         count: 3,
         auto_join_text_default: "",
         auto_join_text_ed: "",
         auto_join_text_ing: "",
         auto_join_text_reply: "",
         auto_join_text_url: "",
         loading_text: "loading tweets..."
       });
     });
	});
	/*
	var head = $('head')[0];
	$(document.createElement('link')).attr({type: 'text/css', href: '/themed/template2/css/jquery.jgrowl.css', rel: 'stylesheet', media: 'screen'}).appendTo(head); 
	*/
	/*$.getScript('/js/jquery.jgrowl_minimized.js', function() {
		setTimeout(cust_growl, 1000);
	});*/
	
}

function cust_growl()
{
	$.jGrowl("Hello world!", { sticky: true, position:'bottom-right'});
}

function show_time()
{
	$.ajax({ 
		url: "/miscellaneous.php",
		data : "q=serv_time",
		cache: false,
		success: function(data){
			$('#serv_time').text(data);
		}
	});
}

function show_bid_balance()
{
	$.ajax({ 
		url: "/bids/ajax_balance",
		cache: false,
		success: function(data){
			$('.bid-balance').text(data);
		}
	});
}

function ctimer()
{
	$('.auction-item').each(function () {
	
        var auctionId    = $(this).attr('id');
		if (auctionObjects[auctionId]['jtime_left'] < 1 && auctionObjects[auctionId]['jclosed'] == 1) {
			return;
		}
		if (auctionObjects[auctionId]['jpeak_only'] == 1 && auctionObjects[auctionId]['jstart_time_status'] != 4) {

		} else {
			st = auctionObjects[auctionId]['jend_time'];
			tsd = st - auctionObjects[auctionId]['jserverTimestamp'];
			if (tsd > 0) {
				var d = new Date();
				d.setTime(auctionObjects[auctionId]['time_d']);
				end_time_string = format_time(d, auctionObjects[auctionId]['time_d_day']);
				auctionObjects[auctionId]['countdown'].html(end_time_string);
				//var d = new Date(auctionObjects[auctionId]['time_d']);
				
				if (auctionObjects[auctionId]['jtime_left'] <= 10) {
					auctionObjects[auctionId]['countdown'].css({'color': '#ffffff', 'background-color':'#ff0000', 'padding-left':'2px', 'padding-right':'2px'});
				} else {
					auctionObjects[auctionId]['countdown'].removeAttr('style');
				}
			} else {
				if (st - auctionObjects[auctionId]['jserverTimestamp'] < -5) {
					auctionObjects[auctionId]['countdown'].removeAttr('style');
					auctionObjects[auctionId]['countdown'].html('checking...');
				}
			}
		}
		auctionObjects[auctionId]['time_d'] = auctionObjects[auctionId]['time_d'] - 1000;
		auctionObjects[auctionId]['jend_time'] = auctionObjects[auctionId]['jend_time'] - 1;
		auctionObjects[auctionId]['jtime_left'] = auctionObjects[auctionId]['jtime_left'] - 1;
	});
}

function format_time(d, day)
{
	hrs = d.getHours();
	mins = d.getMinutes();
	secs = d.getSeconds();
	tm = day+'d '+pad2(hrs)+':'+pad2(mins)+':'+pad2(secs);
	if (day <= 0) {
		tm = pad2(hrs)+':'+pad2(mins)+':'+pad2(secs);
		
		if (hrs <= 0) {
			if (mins <= 0) {
				if (secs <= 0) {
					tm = '1 s';
				} else {
					tm = secs+' s';
				}
			} else {
				if (mins == 1 && secs == 0) {
					tm = '60 s';
				} else {
					tm = mins+' min '+secs+' s';
				}
			}
		} 
	}
			
	return tm;
}

function pad2(number) {
   
     return (number < 10 ? '0' : '') + number
   
}

