﻿var gTransactionFees;
function login()
{
 
    if( $('#txtUsername').val() =='Username' || $('#txtUsername').val() ==''){
        alert("Please enter your username");
        return false;
    }
    
    if($('#txtPassword').val() =='Password' || $('#txtPassword').val() ==''){
        alert("Please enter your password");
        return false;
    }
    
    var xEmailVal = validateEmail( $('#txtUsername').val() );
    if(xEmailVal ==false)
    {
        alert("Please enter valid email address");
        return false;
    }
    
    xUsername = $('#txtUsername').val(); 
    xPassword = $('#txtPassword').val();
        
    var x = {Email:xUsername, Password:xPassword};
    
    $("#btnLogin").attr('value', 'Wait...');
    $("#btnLogin").attr('disabled', true); 
    jQuery.ajax( { type: "POST", url: "/pages/pLogin.aspx", data:x, success: getLogin});
    
}
function getLogin(val)
{
    if (val=="OK")
    {
       $("#loginBox").hide();
       $("#afterlogin").show();
       $("#myName").html( $.cookie("nickName"));
       $("#loginDiv").html('You are logged in now!');
       $("#masterLogin").html("<a href='myaccount.aspx' >My account</a> | <a href='javascript:;' onclick='logout()'>Logout</a>" );
       tb_remove();
    }
    else
    {
        alert(val);
       $("#btnLogin").attr('disabled', false); 
       $("#btnLogin").attr('value', 'Login');
       $("#loginBox").show();
       $("#afterlogin").hide();
       $("#errorMsg").html(val);
       $("#loginerror").html(val);
    }
}
function loginToCheckOut()
{
    if( $('#txtUsername').val() =='Username' || $('#txtUsername').val() ==''){
        alert("Please enter your username");
        return false;
    }
    
    if($('#txtPassword').val() =='Password' || $('#txtPassword').val() ==''){
        alert("Please enter your password");
        return false;
    }
    
    var xEmailVal = validateEmail( $('#txtUsername').val() );
    if(xEmailVal ==false)
    {
        alert("Please enter valid email address");
        return false;
    }
    
    xUsername = $('#txtUsername').val(); 
    xPassword = $('#txtPassword').val();
        
    var x = {Email:xUsername, Password:xPassword};
    
    $("#btnLogin").attr('value', 'Wait...');
    $("#btnLogin").attr('disabled', true); 
    jQuery.ajax( { type: "POST", url: "/pages/pLogin.aspx", data:x, success: getLoginToCheckOut});
}
function getLoginToCheckOut(val)
{
    if (val=="OK")
    {
       $("#loginBox").hide();
       $("#afterlogin").show();
       $("#myName").html( $.cookie("nickName"));
       $("#masterLogin").html("<a href='myaccount.aspx' >My account</a> | <a href='javascript:;' onclick='logout()'>Logout</a>" );
       window.location.href="/Pages/pCheckOut.aspx";
       
    }
    else
    {
       alert(val);   
       $("#btnLogin").attr('disabled', false); 
       $("#loginBox").show();
       $("#afterlogin").hide();
    }
}




function registerMe()
{
    if (! $('#chkTerms').is(":checked"))
    {
        alert("You must agree terms & condition to register.");
        return false;
    }
    if( $('#email').val() ==''){
        alert("Please enter your email");
        return false;
    } 
    if($('#password').val() ==''){
        alert("Please enter your password");
        return false;
    }  
    
    if($('#password').val() != $('#confirm').val() ){
        alert("Your confirm password does not match");
        return false;
    }
     
    
    var xEmailVal = validateEmail( $('#email').val() );
    if(xEmailVal==false)
    {
        alert("Please enter valid email address");
        return false;
    }
    
    if ($('#country').val() == '0')
    {
        alert("Please enter your country");
        return false;
    } 
    xUsername = $('#email').val(); 
    xPassword = $('#password').val();
    xFullname = $('#fullname').val(); 
    xNickname = $('#nickname').val();
    xCountry = $('#country').val();
    xTelno = $('#telno').val();
        
    var x = {Email:xUsername, Password:xPassword, Fullname:xFullname, Nickname:xNickname, Telno:xTelno, Country:xCountry};
    
    $("#regButton").attr('value', 'Wait...');
    $("#regButton").attr('disabled', true); 
    jQuery.ajax( { type: "POST", url: "/pages/pRegister.aspx", data:x, success: getRegister}) ;
}


function getRegister(val)
{
    if (val=="OK")
    {
      $('#regMessage').html('Your account has been created successfully.<br/> Please activate your account by clicking on link sent to your account');
      $('#regDetails').hide();
    }
    else
    {
        $('#regMessage').html(val);
        $("#regButton").attr('value', 'Register');
       $("#regButton").attr('disabled', false);  
    }
}
function UpdateProfile() {
    if ($('#fullname').val() == '') {
        alert("Please enter your full name");
        return false;
    }
    if ($('#nickname').val() == '') {
        alert("Please enter your nick name");
        return false;
    }
    if ($('#telno').val() == '') {
        alert("Please enter your telephone no");
        return false;
    } 
    if ($('#paypal').val() == '') {
        alert("Please enter your paypal account");
        return false;
    }
    if ($('#country').val() == '0') {
        alert("Please select your country");
        return false;
    }
    
    
    
   
    xFullname = $('#fullname').val(); 
    xNickname = $('#nickname').val();
    xCountry = $('#country').val();
    xTelno = $('#telno').val();
    xPaypal = $('#paypal').val();
        
    var x = {Fullname:xFullname, Nickname:xNickname, Telno:xTelno, Country:xCountry,Paypal:xPaypal };
    
    $("#regButton").attr('value', 'Wait...');
    $("#regButton").attr('disabled', true); 
    jQuery.ajax( { type: "POST", url: "/pages/pRegister.aspx?val=update", data:x, success: getUpdateProfile}) ;
}
function getUpdateProfile(val)
{
    if (val=="OK")
    {
       tb_remove();
    }
    else
    {
       alert(val);   
       $("#regButton").attr('disabled', false);  
    }
}



function validateEmail(src) 
{
    var regex = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
    return regex.test(src);
}
var qs;
function getParameter(s) 
{
    if (qs===undefined) 
    {
	    var q = location.search;
	    q = q.substring(1, q.length);
	    var a = q.split("&");
	    qs = new Object();
	    if (a.length>0) {
		    for(var i=0; i<a.length; i++) {
			    var p = a[i].indexOf('=');
			    if (p > 0) {
				    var key = a[i].substring(0,p);
				    var value = a[i].substring(p+1);
				    qs[key] = value;
			    }
		    }
    	}
	}
    var v = qs[s];
    
    if (v===undefined) 
	    v = "";
	    
return v;
}

function isValidNumber(val){ 

var reFloat=/^((\d+(\.\d*)?)|((\d*\.)?\d+))$/;
       return reFloat.test(val)

}

function checkExtImage(formObj)
{
    var filename = formObj.val();
    var filelength = parseInt(filename.length) - 3;
    var fileext = filename.substring(filelength,filelength + 3);
    // Check file extenstion
    if (fileext )
    {
        if (fileext.toLowerCase() != "gif" && fileext.toLowerCase() != "jpg" && fileext.toLowerCase() != "png")
        return false;
        else 
        return true;
    }
    else
    return true
    
}
function checkExtZip(formObj)
{
    var filename = formObj.val();
    var filelength = parseInt(filename.length) - 3;
    var fileext = filename.substring(filelength,filelength + 3);
    // Check file extenstion
    if (fileext)
    {
        if (fileext.toLowerCase() != "zip" && fileext.toLowerCase() != "rar")
        return false;
    else 
        return true;
    }
    else
    return true;
    
}
function checkonLoad() {
    if( ($.cookie("userID") !=null) && ($.cookie("userID")!="")) {
        $("#loginBox").hide();
        $("#afterlogin").show(); 
        $("#myName").html( $.cookie("nickName"));
        
    }
}


function checkMasterLogin()
{
    if( $.cookie("userID") !=null && $.cookie("userID") !="") {
        //$('#cartSpan').show();
        $("#masterLogin").html("<a href='myaccount.aspx' >My account</a> | <a href='javascript:;' onclick='logout()'>Logout</a>" );
    }
}

function getPassword()
{
    
}

 
$(document).ready(function() {
    checkonLoad();
    checkMasterLogin();        
}); 

function makeGrid(tblName)
{
   var tbl = $('#'+tblName); 
   var xCount = tbl[0].rows.length; 
    
   if(xCount > 0)
   {    
	   $(tbl).jTPS( {perPages:[10,20,30,50,'ALL'],scrollStep:1,scrollDelay:30} );
	    $('.GridTable tbody tr:not(.stubCell)').bind('mouseover mouseout',
		    function (e) { e.type == 'mouseover' ? $(this).children('td').addClass('hilightRow') : $(this).children('td').removeClass('hilightRow'); });
   }
   else
   {
	    //alert("no data found");      
        //var firstRow = tbl[0].rows[0];
        //var secondRow = tbl[0].rows[1];
        
        //var secondRows = secondRow.cells[0];
        //$(secondRows).html('<br><center><span class="noRecords">No record found !</span> </center> <br>');
    }	
}


function makeGrid1()
{
    if($('.GridTable1').length)
	{ 
	    var xCount = $('.GridTable1')[0].rows.length; 
 	    
	    if(xCount>2){
	        $('.GridTable1').jTPS( {perPages:[10,15,20,50,'ALL'],scrollStep:1,scrollDelay:30} );
	            $('.GridTable1 tbody tr:not(.stubCell)').bind('mouseover mouseout',
		            function (e) { e.type == 'mouseover' ? $(this).children('td').addClass('hilightRow') : $(this).children('td').removeClass('hilightRow'); }
	        );
	   }
	   else
	   {
	        var firstRow = $('.GridTable1')[0].rows[0];
	        var secondRow = $('.GridTable1')[0].rows[1];
	        
	        var secondRows = secondRow.cells[0];
	        
	        $(firstRow).hide();
	        $(secondRows).html('<br><center><span class="noRecords">No record found !</span> </center> <br>');
	   }	  
	}	
}
function logout()
{
    
    var x = {logout:"yes"};
    jQuery.ajax( { type: "POST", url: "/pages/pLogin.aspx", data:x, success: reloadPage});
}

function reloadPage(val)
{
    
    if (val=="OK")
       window.location.reload();
    else if(val=="Logout")
            window.location.href="default.aspx";
    else
        alert(val) 
}
    
 function showFlshPreview(o) {

     var t = getParameter("type");
     
     //window.open("../flashdemo.aspx?type="+t+"&fl="+o,"Preview", "width=700,height=500");
     window.open("../flashdemo.aspx?type=" + t + "&fl=" + o,"Preview",'menubar=no,location=no,resizable=yes,scrollbars=no,status=no,height=500,width=700');
 }
 
 function clearAllCartItems()
 {
    $.cookie('cartItems', null);
    $.cookie('cartCounter', null);
    $.cookie('totalPrice', null);
      
 }
 //Add to cart functions
/*
function AddTrackToCart(id,projectid,price) {
        
    var isExists=false;
    storedItems= $.cookie('cartItems');  
    storingValue =projectid+"_"+id+ ","+ price+":";
    
    if(storedItems !=null)
    {   
        storedProjects = storedItems.split(":");
        //$.cookie('TotalPrice',Price);
        $(storedProjects).each( function (i)
        { 
            if(storedProjects[i] !=undefined && storedProjects[i] !="" )
			{
			    storedItems = storedProjects[i].split("_");
			    
			    $(storedItems).each( function (j)
                {
                    if(storedItems[i] !=undefined && storedItems[i] !="" )
			        {
                        row = storedItems[j].split(",");
			            if(id == row[0] && projectid==storedItems[0])
			            {
			               //writeMessge("<table><tr><td><img src='/images/already_added.png'></td><td>Already added to cart!</td></tr></table>");
			               isExists=true;
			             }
			            else
			            {
			                if(row[1]!=undefined)
			                {
			                    storingValue +=storedItems[0]+ "_"+ row[0]+ "," +row[1]+ ":"; 
			                    $.cookie('cartItems', storingValue);
			                }
			                //$.cookie('TotalPrice',parseFloat($.cookie('TotalPrice'))+parseFloat(row[1]));
        			     }
               	     }   
               	 });       
	 		}
		}); 
		if(!isExists)
		{
		    alert('Added to cart');
		 }
		    //writeMessge("<table><tr><td><img src='/images/add_to_cart.png'></td><td>Added to cart!</td></tr></table>"); 
		
    }
    else
    {
        $.cookie('cartItems', storingValue);
        alert('Added to cart');
        
//        $.cookie('TotalPrice',parseFloat(Price));
//        writeMessge("<table><tr><td><img src='/images/add_to_cart.png'></td><td>Added to cart!</td></tr></table>"); 
    }
    alert($.cookie('cartItems'));
}*/
 /*
function AddTrackToCart(id,projectid,price) {
    
    var sProjects=new Array();
    var ProjectsItems=new Array();
    var cookItems = new Array();    
    var newcookie="";
    alert(id+','+projectid+','+ price);
    if (($.cookie('cartItems') != null) && ($.cookie('cartItems') != ""))
    {
        sProjects= $.cookie('cartItems').split(":");
        var idExist=false;
        for (j = 0; j <= sProjects.length-1; j++) 
        {
            ProjectsItems= sProjects[j].split("_");
            if (ProjectsItems[0]==projectid) 
            {
                //If project id exist
                idExist=true;
                cookItems = ProjectsItems[1].split(",");
                for (i = 0; i <= cookItems.length-1; i++) 
                {
                    if (id == cookItems[i]) 
                    {
                        alert("Item is already added");
                        return;
                    }
                }   //end of for loop 
                
                var items=ProjectsItems[1]+ "," + id
                ProjectsItems[1]=items
                if ($.cookie('cartCounter') == null) {
                    $.cookie('cartCounter', 1);
                }
                else {
                    var cook = parseInt($.cookie('cartCounter')) + 1;
                    $.cookie('cartCounter', cook);
                }
                if ($.cookie('totalPrice') != null) {
                    $.cookie('totalPrice', (parseFloat($.cookie('totalPrice')) + parseFloat(price)).toFixed(2));
                }
                else {
                    $.cookie('totalPrice', parseFloat(price));
                }
                
                newcookie+=ProjectsItems[0]+"_"+ProjectsItems[1];
                
            }   //end of projectid test if 
            else    
            {
                newcookie=newcookie+sProjects[j]+":";
            }
                
        }   //End of for loop
        
        if (!idExist)
        {
            newcookie=$.cookie('cartItems');
            newcookie=newcookie+":"+projectid+"_"+id+","+price;
        }
            
    }
    else
    {
        newcookie+=newcookie+":"+projectid+"_"+id+","+price;
          if ($.cookie('cartCounter') == null) {
                $.cookie('cartCounter', 1);
            }
            else 
            {
                var cook = parseInt($.cookie('cartCounter')) + 1;
                $.cookie('cartCounter', cook);
            }

            if ($.cookie('totalPrice') != null) {
                $.cookie('totalPrice', (parseFloat($.cookie('totalPrice')) + parseFloat(price)).toFixed(2));
            }
            else {
                $.cookie('totalPrice', parseFloat(price));
            }
    }
    if (newcookie!=null && newcookie!="") 
        $.cookie('cartItems', newcookie);
      
    alert($.cookie('cartItems'));    
    // updating user about added
    //loadCart(); // update    
    $("#message_box").html("Item has been added to cart.");
    $("#message_box").show();
    $("#message_box").fadeOut(5000);


}
*/
function RemoveFromCart(id, projectid,price) {
    
     var sProjects=new Array();
    var ProjectsItems=new Array();
    var cookItems = new Array();    
    var newcookie="";
    if (($.cookie('cartItems') != null) && ($.cookie('cartItems') != ""))
    {
        sProjects= $.cookie('cartItems').split(":");
        var idExist=false;
        for (j = 0; j <= sProjects.length-1; j++) 
        {
            ProjectsItems= sProjects[j].split("_");
            if (ProjectsItems[0]==projectid) 
            {
                //If project id exist
                idExist=true;
                 var items="";
                cookItems = ProjectsItems[1].split(",");
                for (i = 0; i <= cookItems.length-1; i++) 
                {
                    if (id != cookItems[i]) 
                    {
                       items = (items==""?cookItems[i]: "," + cookItems[i]) ;
                        
                    }
                }   //end of for loop 
                   
                ProjectsItems[1]=items
                $.cookie('cartCounter', parseInt(parseInt($.cookie('cartCounter')) - 1));
                $.cookie('totalPrice', (parseFloat($.cookie('totalPrice')) - parseFloat(price)).toFixed(2));
                newcookie+=ProjectsItems[0]+"_"+ProjectsItems[1];
                
            }   //end of projectid test if 
            else    
            {
                newcookie=newcookie+sProjects[j]+":";
            }
                
        }   //End of for loop
        
        if (!idExist)
        {
            newcookie=$.cookie('cartItems');
            newcookie=newcookie+":"+projectid+"_"+id;
        }
        
    }   
       
    if (newcookie!=null && newcookie!="") 
        $.cookie('cartItems', newcookie);

    // updating user about added
    //loadCart(); // update users cart
    $("#message_box").html("Item has beed removed from your  cart.");
    $("#message_box").show();
    $("#message_box").fadeOut(5000);
}

//function loadCart() {
////    if ($.cookie('cartCounter') != null) {
////        $("#cartInfo").html($.cookie('cartCounter') + " items [$" + $.cookie('totalPrice') + "]");
////    } 
//}
//function showCart() {
//    // load cart template 
//    /* $.ajax({ type: "GET",url: "templates/cart.htm",data: "{}",contentType: "application/json; charset=utf-8",// dataType: "json",
//    success: function(msg) 
//    {
//    $("#middleContent").html(msg); // load the page template ContentArea
//    $.ajax({ type: "GET",url: "pages/pViewCart.aspx",contentType: "application/json; charset=utf-8",// dataType: "json",
//    success: function(msg) { $("#cartAreaContent").html(msg); strTracks(); } //
//    });
//    }
//    });     */
//    $.ajax({ type: "GET", url: "pages/pViewCart.aspx", contentType: "application/json; charset=utf-8", // dataType: "json",
//        success: function(msg) { $("#middleContent").html(msg); strTracks(); } //
//    });
//}
////// Below script is to have specific date format.. See http://blog.stevenlevithan.com/archives/date-time-format
var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && (typeof date == "string" || date instanceof String) && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date();
		if (isNaN(date)) throw new SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
    dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};
//Shopping cart
var storedItems = new Array();
var storedProjects = new Array();
var storingValue="";
var row;

function validateTotalCart(id,projectid)
{
    var isValid=true;
    var CartItems= $.cookie('cartItems');  
    if(CartItems !=null)
    {   
        var Projects = CartItems.split(":");
      
        $(Projects).each( function (i)
        { 
            if(Projects[i] !=undefined && Projects[i] !="" )
			{
			            var rows = Projects[i].split(",");
			            if(6 != rows[1] && projectid==rows[0])
			            {
			               isValid=false;
			            }
			            
               	      
	 		}
		}); 
	}
	
	if(isValid)
	    return true;
	else
	    return false; 
    
}
function validateItemCart(id,projectid)
{
    var isValid=true;
    var CartItems= $.cookie('cartItems');  
    if(CartItems !=null)
    {   
        var Projects = CartItems.split(":");
        
        $(Projects).each( function (i)
        { 
            
            if(Projects[i] !=undefined && Projects[i] !="" )
			{
			            var rows = Projects[i].split(",");
			            
			            if(6 == rows[1] && projectid==rows[0])
			            {
			               alert('Total project already added to cart. \n If you need just items, please remove total project from your cart');
			               isValid=false;
			            }
			            
               	      
	 		}
		}); 
	}
	
	if(isValid)
	    return true;
	else
	    return false;    
}
var dRate;
function AddToCart(id,projectid,price,projectname,itemname,priceinRS,discount,commision,Rate) {
    
    var nDiscount=0;
    var nCommision=0;
    
    nCommision=(100*commision)/priceinRS;
    
    if(id==6 && discount!=0) 
    {
        
        nDiscount=(100*discount)/priceinRS;
        priceinRS=priceinRS-((100*discount)/priceinRS);
        
    } 
    
    dRate=Rate;
    if(id==6)
    {
       
        if (!validateTotalCart(id,projectid))
        {
            var answer = confirm ("You have other items already added to the cart.\n Once you buy complete project, others will be removed.")
            if (answer)
            {
                storedItems= $.cookie('cartItems');  
                storingValue =projectid+","+id+ ","+ price+","+projectname+ ","+ itemname+","+ priceinRS+","+ nDiscount+","+ nCommision+":";
                $.cookie('cartItems', storingValue);
                if(storedItems !=null)
                {   
                    storedProjects = storedItems.split(":");
                    $.cookie('TotalPrice',price);
                    $.cookie('TotalPriceInRS',priceinRS);
                    $.cookie('TotalDiscount',parseFloat(nDiscount));
                    $.cookie('TotalCommision',parseFloat(nCommision));
                    $(storedProjects).each( function (i)
                    { 
                        if(storedProjects[i] !=undefined && storedProjects[i] !="" )
			            {
			                        row = storedProjects[i].split(",");
			                        if(projectid==row[0])
			                        {
    			                        
			                        }
			                        else
			                        {
			                            if(row[0]!=undefined)
			                            {
			                                storingValue +=row[0]+ ","+ row[1]+ "," +row[2]+ ","+ row[3]+ "," +row[4]+ "," +row[5]+ "," +row[6]+ "," +row[7]+ ":"; 
			                                $.cookie('cartItems', storingValue);
			                                $.cookie('TotalPrice',parseFloat($.cookie('TotalPrice'))+parseFloat(row[2]));
			                                $.cookie('TotalPriceInRS',parseFloat($.cookie('TotalPriceInRS'))+parseFloat(row[5]));
			                                $.cookie('TotalDiscount',parseFloat($.cookie('TotalDiscount'))+parseFloat(row[6]));
			                                $.cookie('TotalCommision',parseFloat($.cookie('TotalCommision'))+parseFloat(row[7]));
            			                    
			                            }
            			                
        			                 }
                           	      
	 		            }
		            }); 
    		       
		            alert('Added to cart');
		            showCartSummary();
            		
                }
                return true;
            }     
            else
                return false;
        }            
    }
    else
    {
        if (!validateItemCart(id,projectid))
            return false;
    }
        
    
        
    var isExists=false;
    storedItems= $.cookie('cartItems');  
    storingValue =projectid+","+id+ ","+ price+","+projectname+ ","+ itemname+","+ priceinRS+","+ nDiscount+","+ nCommision+":";
    
    if(storedItems !=null)
    {   
        storedProjects = storedItems.split(":");
        $.cookie('TotalPrice',price);
        $.cookie('TotalPriceInRS',priceinRS);
        $.cookie('TotalDiscount',parseFloat(nDiscount));
        $.cookie('TotalCommision',parseFloat(nCommision));
        $(storedProjects).each( function (i)
        { 
            if(storedProjects[i] !=undefined && storedProjects[i] !="" )
			{
			            row = storedProjects[i].split(",");
			            if(id == row[1] && projectid==row[0])
			            {
			               isExists=true;
			               alert('Already added to cart');
			             }
			            else
			            {
			                if(row[0]!=undefined)
			                {
			                    storingValue +=row[0]+ ","+ row[1]+ "," +row[2]+ ","+ row[3]+ "," +row[4]+ "," +row[5]+ "," +row[6]+ "," +row[7]+ ":"; 
			                    $.cookie('cartItems', storingValue);
			                    $.cookie('TotalPrice',parseFloat($.cookie('TotalPrice'))+parseFloat(row[2]));
			                    $.cookie('TotalPriceInRS',parseFloat($.cookie('TotalPriceInRS'))+parseFloat(row[5]));
			                    $.cookie('TotalDiscount',parseFloat($.cookie('TotalDiscount'))+parseFloat(row[6]));
			                    $.cookie('TotalCommision',parseFloat($.cookie('TotalCommision'))+parseFloat(row[7]));
			                    
			                }
			                
        			     }
               	      
	 		}
		}); 
		if(!isExists)
		{
		    alert('Added to cart');
		 }
		    
		
    }
    else
    {
        $.cookie('cartItems', storingValue);
        $.cookie('TotalPrice',parseFloat(price));
        $.cookie('TotalPriceInRS',parseFloat(priceinRS));
        $.cookie('TotalDiscount',parseFloat(nDiscount));
        $.cookie('TotalCommision',parseFloat(nCommision));
        alert('Added to cart');
    }
    showCartSummary();
   
}
function showCart()
{ 

    dRate=49.08;
    var html;
    if($.cookie('cartItems')==null || $.cookie('cartItems')=="")
    {
		html=" <table border=0 align=center width=100%><tr><td class='progress'><img src='/images/cart_icon.jpg'/></td><td><span class='progress'>No items in your cart !</span></td></tr></table>"; 
        
    }
	else
	{	
	    var CartItems=new Array();
	    var items=$.cookie('cartItems');
	    CartItems=items.split(":");  
	    var row;
	    if(CartItems !=null)
	    {
	        html="<table border=0 cellpadding='10' cellspacing='0' width='100%'>";
	        html=html+"<tr class='CartHeader'><td style='margin-left:5px'>Project</td><td>Item</td><td >Price</td><td >Remove</td></tr>";
	        $(CartItems).each( function (i)
            { 
                
                if(CartItems[i] !=undefined && CartItems[i] !="" )
                    {
        		        row = CartItems[i].split(",");
        			    html=html+"<tr><td><div>"+row[3]+"</div></td><td>"+row[4]+"</td><td>Rs."+(parseFloat(row[5]))+"</td><td style='text-align:center'><img style='cursor:pointer' onclick=\"javascript:UpdateCart('"+row[0]+"','"+row[1]+"')\" src='/images/cross.png' /></td></tr>";
        			    html=html+"<tr><td class='hline' colspan='5'></td></tr>";
                    }
             });
             
             html = html + "<tr ><td colspan='4' >"+
                                "<table class='CartTotal' width='100%'><tr>" +
                                            "<td>Total item cost: Rs. " + parseFloat($.cookie('TotalPriceInRS')) + "</td>" +
                                            "<td>Grand Total: Rs. " + (parseFloat($.cookie('TotalPriceInRS')) + parseFloat(gTransactionFees)) +
                                            "</td>" +
                                            
                                         "</tr>"+
                                         "<tr>"+
                                            "<td>Transaction fees: Rs. " + gTransactionFees + "</td>" +
                                            "<td><input type='button'  value='CheckOut' class='button_large' onclick=\"javascript:return checkOut()\"/>"+
                                            "</td>"+
                                         "</tr>"+
	                                "</table>"

                            + "</td></tr >"
             
             /*
             <div class='CartTotal'><span style='float:left;'>Total item cost: Rs. " + parseFloat($.cookie('TotalPriceInRS')) + "</span><br/>Transaction fees: Rs. " + gTransactionFees + "<br/>Grand Total: Rs. " + (parseFloat($.cookie('TotalPriceInRS')) + parseFloat(gTransactionFees)) + "<span id='checkoutButton' style='float:right;margin-right:10px'><input type='button'  value='CheckOut' class='button_large' onclick=\"javascript:return checkOut()\"/></span></div></td></tr>";
             
//             html = html + "<tr ><td colspan='4' >Transaction fees:" + gTransactionFees + "</td></tr >";
//             html = html + "<tr ><td colspan='4' >Grand Total:" + (parseFloat($.cookie('TotalPriceInRS'))+parseFloat(gTransactionFees)) + "</td></tr >";
*/
             html=html+"</table>";
             
         }
	  }
	  $('#cart').html(html);
	  showCartSummary();
} 
function UpdateCart(projectID,itemID)
{
    var answer = confirm("Are you sure want to remove item?");
    
    if (answer)
    {
        storedItems= $.cookie('cartItems'); 
        $.cookie('cartItems',null); 
        $.cookie('TotalPrice',0);
        $.cookie('TotalPriceInRS',0);
        $.cookie('TotalDiscount',0);
        $.cookie('TotalCommision',0);
        storingValue="";
        if(storedItems !=null)
        {   
            storedItems = storedItems.split(":");
            $(storedItems).each( function (i)
            { 
               
			    if(storedItems[i] !=undefined && storedItems[i] !="" )
			    {
    			    
			        row = storedItems[i].split(",");
    			    
			        if(itemID == row[1] && projectID==row[0])
			        {
    			        
			        }
			        else
			        {
			            if(row[0]!=undefined)
		                {
		                    storingValue +=row[0]+ ","+ row[1]+ "," +row[2]+ ","+ row[3]+ "," +row[4]+ "," +row[5]+ "," +row[6]+ "," +row[7]+":"; 
		                    $.cookie('cartItems', storingValue);
		                    $.cookie('TotalPrice',parseFloat($.cookie('TotalPrice'))+parseFloat(row[2]));			        
		                    $.cookie('TotalPriceInRS',parseFloat($.cookie('TotalPriceInRS'))+parseFloat(row[5]));
		                    $.cookie('TotalDiscount',parseFloat($.cookie('TotalDiscount'))+parseFloat(row[6]));
		                    $.cookie('TotalCommision',parseFloat($.cookie('TotalCommision'))+parseFloat(row[7]));
		                }
			            
               	    }
	 		    }
		    }); 
        }
        showCart();
        showCartSummary();
    }    
    else
        return false;
        
}
function showCartSummary()
{
    
    if ($.cookie('cartItems') != null && $.cookie('cartItems') != "")
    {
        var CartItems=new Array();
	    var items=$.cookie('cartItems');
        CartItems=items.split(":");
        
        $('#cartSummary').html('('+(CartItems.length-1)+' items '+ 'Rs.'+ (parseFloat($.cookie('TotalPriceInRS')))+')');
    }
    else
        $('#cartSummary').html('(0 items Rs. 0.00)');
}
function checkOut()
{
    if($.cookie('userID') == null || $.cookie('userID') == "")
    {
       alert("Please login to check out");
       return false;
    }
    //    var cart=$.cookie('cartItems');
//    var amount=parseFloat($.cookie('TotalPrice'));
//    var discount=parseFloat($.cookie('TotalDiscount'));
//    var commision=parseFloat($.cookie('TotalCommision'));
    window.location.href="/Pages/pCheckOut.aspx";
 }
 function chkIsSearch(e)
{
    
   var searchdata=$('#searchbox').val();
     
   var evt = e ? e : window.event; 
   if (evt.keyCode == 13)
   { 
      var TechIds=getSelectedCheckbox();  
      window.location.href="../buyProjects.aspx?type=search&searchdata="+searchdata+"&TechIds="+TechIds;
   } 
}
function getSelectedCheckbox() {
   
   var strTechChecked="";
   var icount=0; 
   for (var i=1; i<=15; i++) 
   {
         if (document.getElementById(i).checked)
         {
           if(icount==0)
           {
            strTechChecked=i;
           }
           else
           {
            strTechChecked=strTechChecked+","+i;
           }
            icount=icount+1;
         }
   }
   
   return strTechChecked;
} 

function searchprojects()
{
    
  var searchdata=$('#searchbox').val();  
  var TechIds=getSelectedCheckbox();  
  window.location.href="../buyProjects.aspx?type=search&searchdata="+searchdata+"&TechIds="+TechIds;
}
function AdminSearch()
{

   var searchdata=$('#searchbox').val();
   window.location.href="Projects.aspx?searchdata="+searchdata;
 
}
function clickButton(e, buttonid)
{
       var evt = e ? e : window.event; 
      var bt = document.getElementById(buttonid);

      if (bt){ 
          if (evt.keyCode == 13){

                bt.click();

                return false;

          } 
      } 
} 
function ShowGrid()
{
    if($('.GridTable').length)
	{ 
	    var xCount = $('.GridTable')[0].rows.length; 
 	    
	    if(xCount>2){
	        $('.GridTable').jTPS( {scrollStep:1,scrollDelay:30} );
	            $('.GridTable tbody tr:not(.stubCell)').bind('mouseover mouseout',
		            function (e) { e.type == 'mouseover' ? $(this).children('td').addClass('hilightRow') : $(this).children('td').removeClass('hilightRow'); }
	        );
	   }
	   else
	   {
	        var firstRow = $('.GridTable')[0].rows[0];
	        var secondRow = $('.GridTable')[0].rows[1];
	        
	        var secondRows = secondRow.cells[0];
	        
	        $(firstRow).hide();
	        $(secondRows).html('<br><center><span class="noRecords">No record found !</span> </center> <br>');
	          
	   }	  
	}	
}

function download(file,itemID)
{
    //make ajax call to update download log
    $.post("/pages/pUpdateDownloadLog.aspx?itemID="+itemID)
         //open download window
    
    window.open('pages/pDownload.aspx?fL='+file,'das','top=1,left=1,scrollbars=no,width=1,height=1');
}
function ResetRegister()
{
  $('#fullname').val("");
  $('#nickname').val("");
  $('#email').val("");
  $('#password').val("");
  $('#confirm').val("");
  $('#telno').val("");
  $('#country').val("0");
  $('#regMessage').html("");  
  
}
//Advanced search for project
document.onclick=check;

var Ary=[];

function check(e) {
 var target = (e && e.target) || (event && event.srcElement);
 while (target.parentNode){
  if (target.className.match('pop')||target.className.match('poplink')) return;
  target=target.parentNode;
 }
 var ary=zxcByClassName('pop')
 for (var z0=0;z0<ary.length;z0++){
  ary[z0].style.display='none';
 }
}
function zxcByClassName(nme,el,tag){
 if (typeof(el)=='string') el=document.getElementById(el);
 el=el||document;
 for (var tag=tag||'*',reg=new RegExp('\\b'+nme+'\\b'),els=el.getElementsByTagName(tag),ary=[],z0=0; z0<els.length;z0++){
  if(reg.test(els[z0].className)) ary.push(els[z0]);
 }
 return ary;
}

function toggle(layer_ref) {
 var hza = document.getElementById(layer_ref);
 if (hza && hza.style){
  if (!hza.set){ hza.set=true;  Ary.push(hza); }
  hza.style.display = (hza.style.display == '')? 'none':'';
 }
}

//



function checkLinkCode()
{

    var orderID = $('#hdnOrder').val();
    var LinkCode = $('#codeLink').val()
    $.post("/pages/pCheckLink.aspx?orderID=" + orderID + "&LinkCode=" + LinkCode,
         function(msg)
         {
             if (msg == "OK")
             {
                 $('#linkcodeDetails').hide();
                 $('#details').show();
                 $.cookie('LinkCode', LinkCode);
             }
             else if (msg == "Expired")
             {
                 $('#linkcodeDetails').hide();
                 $('#details').show();
                  
             }
             else
             {
                 $('#invalidLink').show();
             }
         }
     )

}

function getDateFromPicker(picker)
{
    
    $("#" + picker).datepicker({ dateFormat: 'dd-M-yy' });
}